views.py 31.5 KB
Newer Older
fred's avatar
fred committed
1
from datetime import datetime, timedelta, date
2
import math
fred's avatar
fred committed
3
import random
4 5 6
import os
import stat
import time
7
import urlparse
Simon Daron's avatar
Simon Daron committed
8

fred's avatar
fred committed
9
from django.core.urlresolvers import reverse
fred's avatar
fred committed
10
from django.conf import settings
11
from django.http import Http404
12
from django.views.decorators.cache import cache_control
Simon Daron's avatar
Simon Daron committed
13 14 15
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
16
from django.views.generic.dates import _date_from_string
fred's avatar
fred committed
17
from django.views.generic.dates import MonthArchiveView
Simon Daron's avatar
Simon Daron committed
18

Simon Daron's avatar
Simon Daron committed
19 20
from django.core.paginator import Paginator

fred's avatar
fred committed
21 22
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed, add_domain
23
from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
fred's avatar
fred committed
24

fred's avatar
fred committed
25
from haystack.query import SearchQuerySet
Simon Daron's avatar
Simon Daron committed
26 27
from jsonresponse import to_json

Simon Daron's avatar
Simon Daron committed
28
from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
fred's avatar
fred committed
29
        Schedule, Nonstop, NewsItem, NewsCategory, Focus
Simon Daron's avatar
Simon Daron committed
30

fred's avatar
fred committed
31
from emissions.utils import whatsonair, period_program
Simon Daron's avatar
Simon Daron committed
32

33
from newsletter.forms import SubscribeForm
34
from nonstop.utils import get_current_nonstop_track
fred's avatar
fred committed
35
from nonstop.models import SomaLogLine
36

fred's avatar
fred committed
37 38
from panikombo.models import ItemTopik

fred's avatar
fred committed
39 40
from . import utils

Simon Daron's avatar
Simon Daron committed
41

42
class EmissionMixin:
fred's avatar
fred committed
43
    def get_emission_context(self, emission, episode_ids=None):
44
        context = {}
45 46 47

        # get all episodes, with an additional attribute to get the date of
        # their first diffusion
fred's avatar
fred committed
48 49 50 51 52 53
        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)

54
        context['episodes'] = \
fred's avatar
fred committed
55
                episodes_queryset.extra(select={
56 57 58 59 60
                        'first_diffusion': 'emissions_diffusion.datetime',
                        },
                        select_params=(False, True),
                        where=['''datetime = (SELECT MIN(datetime)
                                                FROM emissions_diffusion
fred's avatar
fred committed
61 62
                                               WHERE episode_id = emissions_episode.id
                                                 AND datetime <= CURRENT_TIMESTAMP)'''],
63
                        tables=['emissions_diffusion'],
64
                    ).order_by('-first_diffusion').distinct()
65

fred's avatar
fred committed
66 67 68 69 70 71 72 73 74 75 76 77 78
        context['futurEpisodes'] = \
                episodes_queryset.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
                                                 AND datetime > CURRENT_TIMESTAMP)'''],
                        tables=['emissions_diffusion'],
                    ).order_by('first_diffusion').distinct()


79 80
        # get all related soundfiles in a single query
        soundfiles = {}
fred's avatar
fred committed
81 82 83 84 85 86 87
        if episode_ids is not None:
            for episode_id in episode_ids:
                soundfiles[episode_id] = None
        else:
            for episode in Episode.objects.filter(emission=emission):
                soundfiles[episode.id] = None

fred's avatar
fred committed
88
        for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
89
                fragment=False, episode__emission=emission):
90 91
            soundfiles[soundfile.episode_id] = soundfile

fred's avatar
fred committed
92
        Episode.set_prefetched_soundfiles(soundfiles)
93

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

96
        return context
97 98 99 100 101 102 103


class EmissionDetailView(DetailView, EmissionMixin):
    model = Emission

    def get_context_data(self, **kwargs):
        context = super(EmissionDetailView, self).get_context_data(**kwargs)
104 105
        context['schedules'] = Schedule.objects.select_related().filter(
                emission=self.object).order_by('rerun', 'datetime')
106
        context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
fred's avatar
fred committed
107 108 109 110 111 112 113
        try:
            nonstop_object = Nonstop.objects.get(slug=self.object.slug)
        except Nonstop.DoesNotExist:
            pass
        else:
            today = date.today()
            dates = [today - timedelta(days=x) for x in range(7)]
114
            if datetime.now().time() < nonstop_object.start:
fred's avatar
fred committed
115 116 117
                dates = dates[1:]
            context['nonstop'] = nonstop_object
            context['nonstop_dates'] = dates
118 119
        context.update(self.get_emission_context(self.object))
        return context
120 121
emission = EmissionDetailView.as_view()

122
class EpisodeDetailView(DetailView, EmissionMixin):
123 124 125 126
    model = Episode

    def get_context_data(self, **kwargs):
        context = super(EpisodeDetailView, self).get_context_data(**kwargs)
fred's avatar
fred committed
127 128
        context['diffusions'] = Diffusion.objects.select_related().filter(
                episode=self.object.id).order_by('datetime')
129
        try:
130
            context['emission'] = context['episode'].emission
131 132
        except Emission.DoesNotExist:
            raise Http404()
133 134
        if self.kwargs.get('emission_slug') != context['emission'].slug:
            raise Http404()
135
        context.update(self.get_emission_context(context['emission']))
fred's avatar
fred committed
136
        context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
137 138 139
        return context
episode = EpisodeDetailView.as_view()

Simon Daron's avatar
Simon Daron committed
140

fred's avatar
fred committed
141 142 143 144 145
class NonstopPlaylistView(TemplateView):
    template_name = 'nonstop_playlist.html'

    def get_context_data(self, **kwargs):
        context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
146 147 148 149
        try:
            context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
        except Emission.DoesNotExist:
            raise Http404()
fred's avatar
fred committed
150 151
        context['date'] = date(int(kwargs.get('year')),
                int(kwargs.get('month')), int(kwargs.get('day')))
152
        context['future'] = (context['date'] >= date.today())
fred's avatar
fred committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

        nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
        start = datetime(
                int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
                nonstop_object.start.hour, nonstop_object.start.minute)
        end = datetime(
                int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
                nonstop_object.end.hour, nonstop_object.end.minute)
        if end < start:
            end = end + timedelta(days=1)
        context['tracks'] = SomaLogLine.objects.filter(
                play_timestamp__gte=start,
                play_timestamp__lte=end,
                on_air=True).select_related()
        return context

nonstop_playlist = NonstopPlaylistView.as_view()

171 172 173 174 175 176
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)
177 178
        context['schedules'] = Schedule.objects.select_related().filter(
                emission=self.object).order_by('rerun', 'datetime')
fred's avatar
fred committed
179 180 181 182

        context['search_query'] = self.request.GET.get('q')
        if context['search_query']:
            # query string
183
            sqs = SearchQuerySet().models(Episode).filter(
fred's avatar
fred committed
184
                    emission_slug_exact=self.object.slug, text=context['search_query'])
fred's avatar
fred committed
185 186 187 188 189
            episode_ids = [x.pk for x in sqs]
        else:
            episode_ids = None

        context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
190 191 192
        return context
emissionEpisodes = EmissionEpisodesDetailView.as_view()

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225

class SoundFileEmbedView(DetailView):
    model = SoundFile
    template_name = 'soundfiles/embed.html'

    def get_context_data(self, **kwargs):
        context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
        if self.kwargs.get('episode_slug') != self.object.episode.slug:
            raise Http404()
        if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
            raise Http404()
        context['episode'] = self.object.episode
        return context
soundfile_embed = SoundFileEmbedView.as_view()


class SoundFileDialogEmbedView(DetailView):
    model = SoundFile
    template_name = 'soundfiles/dialog-embed.html'

    def get_context_data(self, **kwargs):
        context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
        if self.kwargs.get('episode_slug') != self.object.episode.slug:
            raise Http404()
        if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
            raise Http404()
        context['episode'] = self.object.episode
        context['site_url'] = self.request.build_absolute_uri('/').strip('/')
        return context
soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()



Simon Daron's avatar
Simon Daron committed
226 227 228
class ProgramView(TemplateView):
    template_name = 'program.html'

Simon Daron's avatar
Simon Daron committed
229
    def get_context_data(self, year=None, week=None, **kwargs):
Simon Daron's avatar
Simon Daron committed
230
        context = super(ProgramView, self).get_context_data(**kwargs)
fred's avatar
fred committed
231

Simon Daron's avatar
Simon Daron committed
232
        context['weekday'] = datetime.today().weekday()
fred's avatar
fred committed
233 234 235 236 237 238

        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)

Simon Daron's avatar
Simon Daron committed
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
        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)

        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():
fred's avatar
fred committed
289 290
            if nonstop.start == nonstop.end:
                continue
Simon Daron's avatar
Simon Daron committed
291 292 293
            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
294
                                 nonstop.title, nonstop.slug])
Simon Daron's avatar
Simon Daron committed
295 296 297 298
            else:
                # crossing midnight
                nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
                                 24,
fred's avatar
fred committed
299
                                 nonstop.title, nonstop.slug])
Simon Daron's avatar
Simon Daron committed
300 301
                nonstops.append([0,
                                 nonstop.end.hour + nonstop.end.minute/60.,
fred's avatar
fred committed
302
                                 nonstop.title, nonstop.slug])
Simon Daron's avatar
Simon Daron committed
303 304 305 306 307 308 309 310 311 312
        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
313
                time_cell.nonstop_slug = nonstop[3]
Simon Daron's avatar
Simon Daron committed
314 315 316 317 318 319
                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])

320 321
        for schedule in Schedule.objects.prefetch_related(
                'emission__categories').select_related().order_by('datetime'):
Simon Daron's avatar
Simon Daron committed
322 323 324 325 326 327 328 329 330 331 332 333
            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]

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
        # 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
353 354 355 356 357 358 359 360 361 362 363
                        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)

364 365 366 367 368 369 370
                        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
371 372 373

        # 1st thing is to merge cells on the same line, this will mostly catch
        # consecutive nonstop cells
Simon Daron's avatar
Simon Daron committed
374 375 376 377 378 379
        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
380 381
                    # if the cells are identical, they are removed from the
                    # grid, and current cell width is increased
Simon Daron's avatar
Simon Daron committed
382 383 384 385 386 387
                    while grid[i][j+t] == cell:
                        cell.w += 1
                        grid[i][j+t] = None
                        t += 1
                except IndexError:
                    pass
fred's avatar
fred committed
388 389

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

fred's avatar
fred committed
392 393
        # 2nd thing is to merge cells vertically, this is emissions that last
        # for more than 30 minutes
Simon Daron's avatar
Simon Daron committed
394 395 396 397 398 399 400 401
        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
402
                        # we look if the next time cell has the same emissions
Simon Daron's avatar
Simon Daron committed
403 404
                        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
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
                        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)
436
                            current_cell_emissions = set([x.emission for x in current_cell_schedules])
fred's avatar
fred committed
437 438 439 440 441 442 443
                            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]
444 445 446
                                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
447 448 449 450
                                    # 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)
451 452
                                elif same_cell_below_emissions and \
                                        current_cell_emissions.issuperset(same_cell_below_emissions):
fred's avatar
fred committed
453
                                    # this handles case B (see comment above)
454 455
                                    # we set the cell time label to the longest
                                    # period
fred's avatar
fred committed
456
                                    grid[i][j].time_label = same_cell_below.time_label
fred's avatar
fred committed
457 458 459 460
                                    # 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()))
461 462 463 464 465 466 467 468 469 470 471
                                    # 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
472 473
                                    grid[i][j].h += 1
                                    grid[i+cursor].remove(same_cell_below)
474 475 476 477 478 479 480
                                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
481
                                cursor += 1
Simon Daron's avatar
Simon Daron committed
482 483 484 485 486 487 488 489 490 491
                            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
492
        context['categories'] = Category.objects.all()
Simon Daron's avatar
Simon Daron committed
493 494 495 496 497 498 499 500 501 502 503 504 505
        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)
506
        context['emissions'] = Emission.objects.filter(archived=False).order_by('-creation_timestamp')[:3]
507
        context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')[:3]
508

509 510
        context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
                podcastable=True, fragment=False) \
511 512 513 514 515 516
                .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)'''],
517
                    tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
518

519 520
        context['newsletter_form'] = SubscribeForm()

Simon Daron's avatar
Simon Daron committed
521 522 523 524
        return context

home = Home.as_view()

Simon Daron's avatar
Simon Daron committed
525
class NewsItemView(DetailView):
Simon Daron's avatar
Simon Daron committed
526 527
    model = NewsItem
    def get_context_data(self, **kwargs):
Simon Daron's avatar
Simon Daron committed
528
        context = super(NewsItemView, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
529
        context['categories'] = NewsCategory.objects.all()
530
        context['news'] = NewsItem.objects.all().order_by('-date')
fred's avatar
fred committed
531
        context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
Simon Daron's avatar
Simon Daron committed
532
        return context
Simon Daron's avatar
Simon Daron committed
533
newsitemview = NewsItemView.as_view()
Simon Daron's avatar
Simon Daron committed
534

Simon Daron's avatar
Simon Daron committed
535 536 537 538
class News(TemplateView):
    template_name = 'news.html'
    def get_context_data(self, **kwargs):
        context = super(News, self).get_context_data(**kwargs)
539 540
        context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
        context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
Simon Daron's avatar
Simon Daron committed
541 542 543 544
        return context

news = News.as_view()

545

fred's avatar
fred committed
546 547 548 549
class Agenda(TemplateView):
    template_name = 'agenda.html'
    def get_context_data(self, **kwargs):
        context = super(Agenda, self).get_context_data(**kwargs)
550
        context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
fred's avatar
fred committed
551
                event_date__gte=date.today()).order_by('date')[:20]
552
        context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
fred's avatar
fred committed
553
        context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
fred's avatar
fred committed
554 555 556 557 558
        return context

agenda = Agenda.as_view()


fred's avatar
fred committed
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
class AgendaByMonth(MonthArchiveView):
    template_name = 'agenda.html'
    queryset = NewsItem.objects.filter(event_date__isnull=False)
    allow_future = True
    date_field = 'event_date'
    month_format = '%m'

    def get_context_data(self, **kwargs):
        context = super(AgendaByMonth, self).get_context_data(**kwargs)
        context['agenda'] = context['object_list']
        context['news'] = NewsItem.objects.all().order_by('-date')
        return context

agenda_by_month = AgendaByMonth.as_view()


Simon Daron's avatar
Simon Daron committed
575 576 577 578 579
class Emissions(TemplateView):
    template_name = 'emissions.html'

    def get_context_data(self, **kwargs):
        context = super(Emissions, self).get_context_data(**kwargs)
580
        context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
Simon Daron's avatar
Simon Daron committed
581
        context['categories'] = Category.objects.all()
Simon Daron's avatar
Simon Daron committed
582 583 584 585
        return context

emissions = Emissions.as_view()

586
class EmissionsArchives(TemplateView):
587
    template_name = 'emissions/archives.html'
588

Simon Daron's avatar
Simon Daron committed
589
    def get_context_data(self, **kwargs):
590
        context = super(EmissionsArchives, self).get_context_data(**kwargs)
fred's avatar
fred committed
591
        context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
592
        context['categories'] = Category.objects.all()
Simon Daron's avatar
Simon Daron committed
593
        return context
594 595
emissionsArchives = EmissionsArchives.as_view()

Simon Daron's avatar
Simon Daron committed
596

Simon Daron's avatar
Simon Daron committed
597 598 599 600 601
class Listen(TemplateView):
    template_name = 'listen.html'

    def get_context_data(self, **kwargs):
        context = super(Listen, self).get_context_data(**kwargs)
602 603
        context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
                podcastable=True, got_focus__isnull=False) \
604 605 606 607 608 609
                .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)'''],
610
                    tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
611 612 613 614 615 616 617 618
        context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
                podcastable=True) \
                .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)'''],
fred's avatar
fred committed
619
                    tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
620

fred's avatar
fred committed
621

Simon Daron's avatar
Simon Daron committed
622 623 624 625
        return context

listen = Listen.as_view()

626
@cache_control(max_age=15)
Simon Daron's avatar
Simon Daron committed
627 628 629 630 631 632 633 634 635 636
@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'):
fred's avatar
fred committed
637 638 639
        chat_url = None
        if d['emission'].chat_open:
            chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
Simon Daron's avatar
Simon Daron committed
640 641
        d['emission'] = {
            'title': d['emission'].title,
fred's avatar
fred committed
642 643
            'url': d['emission'].get_absolute_url(),
            'chat': chat_url,
Simon Daron's avatar
Simon Daron committed
644
        }
fred's avatar
fred committed
645 646 647 648
    if d.get('nonstop'):
        d['nonstop'] = {
            'title': d['nonstop'].title,
        }
649
        d.update(get_current_nonstop_track())
fred's avatar
fred committed
650
    if d.get('current_slot'):
fred's avatar
fred committed
651
        del d['current_slot']
Simon Daron's avatar
Simon Daron committed
652 653 654 655 656 657 658
    return d


class NewsItemDetailView(DetailView):
    model = NewsItem

newsitem = NewsItemDetailView.as_view()
fred's avatar
fred committed
659

660 661 662 663 664 665 666 667 668 669
class RssCustomPodcastsFeed(Rss201rev2Feed):
    def root_attributes(self):
        attrs = super(RssCustomPodcastsFeed, self).root_attributes()
        attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
        return attrs

    def add_item_elements(self, handler, item):
        super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
        for tag in item.get('tags') or []:
            handler.addQuickElement('dc:subject', tag)
fred's avatar
fred committed
670

671 672 673 674
class PodcastsFeed(Feed):
    title = 'Radio Panik - Podcasts'
    link = '/'
    description_template = 'feed/soundfile.html'
675
    feed_type = RssCustomPodcastsFeed
fred's avatar
fred committed
676

677 678 679 680 681 682 683 684
    def items(self):
        return SoundFile.objects.select_related().filter(
                podcastable=True).order_by('-creation_timestamp')[:5]

    def item_title(self, item):
        if item.fragment:
            return '%s - %s' % (item.title, item.episode.title)
        return item.episode.title
fred's avatar
fred committed
685

686 687 688 689
    def item_link(self, item):
        return item.episode.get_absolute_url()

    def item_enclosure_url(self, item):
fred's avatar
fred committed
690 691
        current_site = Site.objects.get(id=settings.SITE_ID)
        return add_domain(current_site.domain, item.get_format_url('mp3'))
692 693 694 695 696 697 698 699

    def item_enclosure_length(self, item):
        sound_path = item.get_format_path('mp3')
        try:
            return os.stat(sound_path)[stat.ST_SIZE]
        except OSError:
            return 0

fred's avatar
fred committed
700
    def item_enclosure_mime_type(self, item):
701 702 703 704 705
        return 'audio/mpeg'

    def item_pubdate(self, item):
        return item.creation_timestamp

706 707 708
    def item_extra_kwargs(self, item):
        return {'tags': [x.name for x in item.episode.tags.all()]}

709
podcasts_feed = PodcastsFeed()
fred's avatar
fred committed
710 711


fred's avatar
fred committed
712 713 714
class RssNewsFeed(Feed):
    title = 'Radio Panik'
    link = '/news/'
715
    description_template = 'feed/newsitem.html'
fred's avatar
fred committed
716 717 718 719 720 721

    def items(self):
        return NewsItem.objects.order_by('-date')[:10]

rss_news_feed = RssNewsFeed()

722 723 724 725 726 727 728
class Atom1FeedWithBaseXml(Atom1Feed):
    def root_attributes(self):
        root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
        scheme, netloc, path, params, query, fragment  = urlparse.urlparse(self.feed['feed_url'])
        root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
        return root_attributes

fred's avatar
fred committed
729
class AtomNewsFeed(RssNewsFeed):
730
    feed_type = Atom1FeedWithBaseXml
fred's avatar
fred committed
731 732

atom_news_feed = AtomNewsFeed()
fred's avatar
fred committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760



class Party(TemplateView):
    template_name = 'party.html'

    def get_context_data(self, **kwargs):
        context = super(Party, self).get_context_data(**kwargs)
        t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
        focus = Focus()
        if t == 'newsitem':
            focus.newsitem = NewsItem.objects.exclude(
                    image__isnull=True).exclude(image__exact='').order_by('?')[0]
        elif t == 'emission':
            focus.emission = Emission.objects.exclude(
                    image__isnull=True).exclude(image__exact='').order_by('?')[0]
        elif t == 'episode':
            focus.episode = Episode.objects.exclude(
                    image__isnull=True).exclude(image__exact='').order_by('?')[0]
        elif t == 'soundfile':
            focus.soundfile = SoundFile.objects.exclude(
                    episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]

        context['focus'] = focus

        return context

party = Party.as_view()
fred's avatar
fred committed
761 762 763 764 765 766 767 768



class Chat(DetailView, EmissionMixin):
    model = Emission
    template_name = 'chat.html'

chat = Chat.as_view()