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

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
7
from django.views.generic.dates import _date_from_string
Simon Daron's avatar
Simon Daron committed
8

Simon Daron's avatar
Simon Daron committed
9 10
from django.core.paginator import Paginator

Simon Daron's avatar
Simon Daron committed
11 12
from jsonresponse import to_json

Simon Daron's avatar
Simon Daron committed
13
from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
Simon Daron's avatar
Simon Daron committed
14 15
        Schedule, Nonstop, NewsItem, NewsCategory

fred's avatar
fred committed
16
from emissions.utils import whatsonair, period_program
Simon Daron's avatar
Simon Daron committed
17 18 19 20 21 22

class ProgramView(TemplateView):
    template_name = 'program.html'

    def get_context_data(self, **kwargs):
        context = super(ProgramView, self).get_context_data(**kwargs)
23
        schedules = Schedule.objects.select_related().order_by('datetime')
Simon Daron's avatar
Simon Daron committed
24 25 26 27 28 29 30 31 32
        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
        return context

program = ProgramView.as_view()

fred's avatar
fred committed
33 34 35 36 37 38

class ProgramWeekView(TemplateView):
    template_name = 'week.html'

    def get_context_data(self, year, week, **kwargs):
        context = super(ProgramWeekView, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
39 40
        context['week'] = week
        context['year'] = year
fred's avatar
fred committed
41 42 43 44
        return context

week = ProgramWeekView.as_view()

Simon Daron's avatar
Simon Daron committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
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():
            if nonstop.start < nonstop.end:
                nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
                                 nonstop.end.hour + nonstop.end.minute/60.,
                                 nonstop.title])
            else:
                # crossing midnight
                nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
                                 24,
                                 nonstop.title])
                nonstops.append([0,
                                 nonstop.end.hour + nonstop.end.minute/60.,
                                 nonstop.title])
        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]
                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])

119
        for schedule in Schedule.objects.select_related().order_by('datetime'):
Simon Daron's avatar
Simon Daron committed
120 121 122 123 124 125 126 127 128 129 130 131 132
            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]

        # merge adjacent cells
fred's avatar
fred committed
133 134 135

        # 1st thing is to merge cells on the same line, this will mostly catch
        # consecutive nonstop cells
Simon Daron's avatar
Simon Daron committed
136 137 138 139 140 141
        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
142 143
                    # if the cells are identical, they are removed from the
                    # grid, and current cell width is increased
Simon Daron's avatar
Simon Daron committed
144 145 146 147 148 149
                    while grid[i][j+t] == cell:
                        cell.w += 1
                        grid[i][j+t] = None
                        t += 1
                except IndexError:
                    pass
fred's avatar
fred committed
150 151

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

fred's avatar
fred committed
154 155
        # 2nd thing is to merge cells vertically, this is emissions that last
        # for more than 30 minutes
Simon Daron's avatar
Simon Daron committed
156 157 158 159 160 161 162 163
        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
164
                        # we look if the next time cell has the same emissions
Simon Daron's avatar
Simon Daron committed
165 166
                        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
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
                        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)
                            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]
                                if current_cell_schedules.issubset(same_cell_below.schedules):
                                    # 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)
                                elif same_cell_below.schedules and \
                                        current_cell_schedules.issuperset(same_cell_below.schedules):
                                    # this handles case B (see comment above)
213 214
                                    # we set the cell time label to the longest
                                    # period
fred's avatar
fred committed
215
                                    grid[i][j].time_label = same_cell_below.time_label
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
                                    # 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
231 232 233
                                    grid[i][j].h += 1
                                    grid[i+cursor].remove(same_cell_below)
                                cursor += 1
Simon Daron's avatar
Simon Daron committed
234 235 236 237 238 239 240 241 242 243
                            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
244
        context['categories'] = Category.objects.all()
Simon Daron's avatar
Simon Daron committed
245 246 247 248 249 250 251 252 253 254 255 256 257
        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
258
        context['newsImaged'] = list(NewsItem.objects.all().exclude(image__isnull=True).exclude(image__exact='').order_by('-datetime')[:3])
Simon Daron's avatar
Simon Daron committed
259
        context['newsImaged2'] = list(NewsItem.objects.all().exclude(image__isnull=True).exclude(image__exact='').order_by('-datetime')[3:15])
Simon Daron's avatar
Simon Daron committed
260
        context['news'] = list(NewsItem.objects.all().order_by('-datetime')[:36])
261
        context['emissions'] = list(Emission.objects.filter(archived=False).order_by('title'))
Simon Daron's avatar
Simon Daron committed
262 263 264 265 266 267
        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
Simon Daron's avatar
Simon Daron committed
268 269 270 271 272 273 274 275 276
        return context

home = Home.as_view()

class News(TemplateView):
    template_name = 'news.html'

    def get_context_data(self, **kwargs):
        context = super(News, self).get_context_data(**kwargs)
277 278 279
        context['newsImaged'] = list(NewsItem.objects.all().exclude(image__isnull=True).exclude(image__exact='').order_by('-datetime')[:3])
        context['news'] = list(NewsItem.objects.all().order_by('-datetime')[:60])
        context['categories'] = list(NewsCategory.objects.all())
Simon Daron's avatar
Simon Daron committed
280 281 282 283
        return context

news = News.as_view()

Simon Daron's avatar
Simon Daron committed
284 285 286 287 288 289 290 291 292 293
class Emissions(TemplateView):
    template_name = 'emissions.html'

    def get_context_data(self, **kwargs):
        context = super(Emissions, self).get_context_data(**kwargs)
        context['emissions'] = Emission.objects.all().order_by('title')
        return context

emissions = Emissions.as_view()

Simon Daron's avatar
Simon Daron committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
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
309
        context['sounds'] = SoundFile.objects.all()[:15]
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
        listenable = []
        x=0
        for episode in Episode.objects.all().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').reverse():
            if x >= 24:
		break
            elif episode.has_sound is None:
		continue
            else:
                x+=1
                listenable .append(episode)
		
        context['episodes'] = listenable
Simon Daron's avatar
Simon Daron committed
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
        return context

listen = Listen.as_view()


@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
349 350 351 352 353
    if d.get('nonstop'):
        d['nonstop'] = {
            'title': d['nonstop'].title,
        }
    if d.get('current_slot'):
fred's avatar
fred committed
354
        del d['current_slot']
Simon Daron's avatar
Simon Daron committed
355 356 357 358 359 360 361
    return d


class NewsItemDetailView(DetailView):
    model = NewsItem

newsitem = NewsItemDetailView.as_view()