views.py 7.92 KB
Newer Older
1
from datetime import datetime, timedelta
Simon Daron's avatar
Simon Daron committed
2
import math, uuid
fred's avatar
fred committed
3

fred's avatar
fred committed
4
from django.views.generic.base import TemplateView
fred's avatar
fred committed
5
from django.views.generic.detail import DetailView
fred's avatar
fred committed
6 7 8
from django.views.decorators.csrf import csrf_exempt

from jsonresponse import to_json
fred's avatar
fred committed
9

10 11
from emissions.models import Emission, Episode, Diffusion, SoundFile, \
        Schedule, Nonstop, NewsItem, NewsCategory
Simon Daron's avatar
Simon Daron committed
12

fred's avatar
fred committed
13
from emissions.utils import whatsonair
fred's avatar
fred committed
14 15 16 17 18 19 20 21 22 23

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

    def get_context_data(self, **kwargs):
        context = super(ProgramView, self).get_context_data(**kwargs)
        schedules = Schedule.objects.all().order_by('datetime')
        days = []
        for day in range(7):
            days.append({'schedules': [x for x in schedules if x.is_on_weekday(day+1)],
24
                         'datetime': datetime(2007, 1, day+1)})
fred's avatar
fred committed
25 26 27 28 29
        context['days'] = days
        return context

program = ProgramView.as_view()

fred's avatar
fred committed
30 31 32 33 34
class TimeCell:
    emissions = None
    nonstop = None
    w = 1
    h = 1
35
    time_label = None
fred's avatar
fred committed
36

fred's avatar
fred committed
37 38 39
    def __init__(self, i, j):
        self.x = i
        self.y = j
40 41 42
        self.schedules = []

    def add_schedule(self, schedule):
43
        end_time = schedule.datetime + timedelta(
44
                minutes=schedule.get_duration())
45 46 47 48 49 50
        self.time_label = '%02d:%02d-%02d:%02d' % (
                schedule.datetime.hour,
                schedule.datetime.minute,
                end_time.hour,
                end_time.minute)
        self.schedules.append(schedule)
fred's avatar
fred committed
51 52

    def __unicode__(self):
53 54
        if self.schedules:
            return ', '.join([x.emission.title for x in self.schedules])
fred's avatar
fred committed
55 56 57 58
        else:
            return self.nonstop

    def __eq__(self, other):
59
        return (unicode(self) == unicode(other) and self.time_label == other.time_label)
fred's avatar
fred committed
60 61 62 63 64 65 66 67 68 69 70 71


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

    def get_context_data(self, **kwargs):
        context = super(Grid, self).get_context_data(**kwargs)
        schedules = Schedule.objects.all().order_by('datetime')

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

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

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
        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()
fred's avatar
fred committed
91 92 93 94

        for i in range(nb_lines):
            grid.append([])
            for j in range(7):
fred's avatar
fred committed
95
                grid[-1].append(TimeCell(i, j))
fred's avatar
fred committed
96 97 98 99

            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]
100 101 102 103 104
                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])
fred's avatar
fred committed
105 106 107 108 109 110

        for schedule in Schedule.objects.all():
            row_start = schedule.datetime.hour * 2 + \
                    int(math.ceil(schedule.datetime.minute / 30))
            day_no = schedule.get_weekday()

111
            for step in range(int(math.ceil(schedule.get_duration() / 30.))):
112 113
                if grid[(row_start+step)%nb_lines][day_no] is None:
                    grid[(row_start+step)%nb_lines][day_no] = TimeCell()
114
                grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
fred's avatar
fred committed
115

116 117
        # start grid after the night programs
        grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
fred's avatar
fred committed
118

fred's avatar
fred committed
119
        # merge adjacent cells
fred's avatar
fred committed
120 121 122 123 124 125 126 127 128 129 130 131
        for i in range(nb_lines):
            for j, cell in enumerate(grid[i]):
                if grid[i][j] is None:
                    continue
                t = 1
                try:
                    while grid[i][j+t] == cell:
                        cell.w += 1
                        grid[i][j+t] = None
                        t += 1
                except IndexError:
                    pass
fred's avatar
fred committed
132
            grid[i] = [x for x in grid[i] if x is not None]
fred's avatar
fred committed
133 134 135 136 137 138 139 140

        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:
fred's avatar
fred committed
141 142 143 144 145 146 147
                    while True:
                        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]
                        if not same_cell_below:
                            break
                        bj, same_cell_below = same_cell_below[0]
                        del grid[i+cell.h][bj]
fred's avatar
fred committed
148 149 150 151
                        cell.h += 1
                except IndexError:
                    pass

fred's avatar
fred committed
152 153 154 155
        # cut night at 3am
        grid = grid[:42]
        times = times[:42]

fred's avatar
fred committed
156
        context['grid'] = grid
fred's avatar
fred committed
157
        context['times'] = times
158 159
        context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
                'Vendredi', 'Samedi', 'Dimanche']
fred's avatar
fred committed
160 161 162 163 164

        return context

grid = Grid.as_view()

165

fred's avatar
fred committed
166 167 168
class Home(TemplateView):
    template_name = 'home.html'

169 170
    def get_context_data(self, **kwargs):
        context = super(Home, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
171 172
        context['newsImaged'] = NewsItem.objects.all().exclude(image__isnull=True).exclude(image__exact='').order_by('-datetime')[:3]
        context['news'] = NewsItem.objects.all().order_by('-datetime')[:60]
Simon Daron's avatar
Simon Daron committed
173
        context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
fred's avatar
fred committed
174
        context['player'] = audioPlayer()
175 176
        return context

fred's avatar
fred committed
177
home = Home.as_view()
178

Simon Daron's avatar
Simon Daron committed
179 180 181 182 183
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
184 185 186
        context['newsImaged'] = NewsItem.objects.all().exclude(image__isnull=True).exclude(image__exact='').order_by('-datetime')[:3]
        context['news'] = NewsItem.objects.all().order_by('-datetime')[:60]
        context['categories'] = NewsCategory.objects.all()
Simon Daron's avatar
Simon Daron committed
187
        context['emissions'] = Emission.objects.filter(archived=False).order_by('?')
fred's avatar
fred committed
188
        context['player'] = audioPlayer()
Simon Daron's avatar
Simon Daron committed
189 190 191 192
        return context

news = News.as_view()

193 194 195 196 197 198 199 200 201
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()
Simon Daron's avatar
Simon Daron committed
202

Simon Daron's avatar
Simon Daron committed
203 204
class Listen(TemplateView):
    template_name = 'listen.html'
205 206

    def get_context_data(self, **kwargs):
Simon Daron's avatar
Simon Daron committed
207
        context = super(Listen, self).get_context_data(**kwargs)
fred's avatar
fred committed
208 209
        context['player'] = audioPlayer()
        return context
Simon Daron's avatar
Simon Daron committed
210

Simon Daron's avatar
Simon Daron committed
211
listen = Listen.as_view()
212

Simon Daron's avatar
Simon Daron committed
213 214 215 216
class audioPlayer:
    def __init__(self):
        self.unique = uuid.uuid4()

217

fred's avatar
fred committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
@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()
        }
    return d
fred's avatar
fred committed
233 234 235 236 237 238


class NewsItemDetailView(DetailView):
    model = NewsItem

newsitem = NewsItemDetailView.as_view()