views.py 7.5 KB
Newer Older
1
from datetime import datetime, timedelta
fred's avatar
fred committed
2
import math
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
6
7
from django.views.decorators.csrf import csrf_exempt

from jsonresponse import to_json
fred's avatar
fred committed
8

9
from emissions.models import Emission, Episode, Diffusion, SoundFile, Schedule
fred's avatar
fred committed
10
from emissions.utils import whatsonair
fred's avatar
fred committed
11
12
13
14
15
16
17
18
19
20

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)],
21
                         'datetime': datetime(2007, 1, day+1)})
fred's avatar
fred committed
22
23
24
25
26
        context['days'] = days
        return context

program = ProgramView.as_view()

fred's avatar
fred committed
27
28
29
30
31
class TimeCell:
    emissions = None
    nonstop = None
    w = 1
    h = 1
32
    time_label = None
fred's avatar
fred committed
33

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

    def add_schedule(self, schedule):
40
        end_time = schedule.datetime + timedelta(
41
42
43
44
45
46
47
                minutes=schedule.emission.duration)
        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
48
49

    def __unicode__(self):
50
51
        if self.schedules:
            return ', '.join([x.emission.title for x in self.schedules])
fred's avatar
fred committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
        else:
            return self.nonstop

    def __eq__(self, other):
        return (unicode(self) == unicode(other))


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
69
        times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
70
71
        # start grid after the night programs
        times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
fred's avatar
fred committed
72

fred's avatar
fred committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
        nonstops = [[0, 2, 'Biodiversite'],
                    [2, 5, 'Reveries'],
                    [5, 7.5, 'La Panique'],
                    [7.5, 10, 'Matin tranquille'],
                    [10, 12, 'Up Beat Tempo'],
                    [12, 13, 'L\'heure de pointe'],
                    [13, 16, 'Le Mange Disque'],
                    [16, 19, 'Hop Bop and co'],
                    [19, 22, 'Acouphene'],
                    [22, 24, 'Biodiversite']
                   ]

        for i in range(nb_lines):
            grid.append([])
            for j in range(7):
fred's avatar
fred committed
88
                grid[-1].append(TimeCell(i, j))
fred's avatar
fred committed
89
90
91
92

            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]
93
94
                if nonstop[2] == 'Reveries':
                    time_cell.time_label = '02:00-05:00'
fred's avatar
fred committed
95
96
97
98
99
100
101

        for schedule in Schedule.objects.all():
            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.emission.duration / 30))):
102
103
                if grid[(row_start+step)%nb_lines][day_no] is None:
                    grid[(row_start+step)%nb_lines][day_no] = TimeCell()
104
                grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
fred's avatar
fred committed
105

106
107
        # start grid after the night programs
        grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
fred's avatar
fred committed
108

fred's avatar
fred committed
109
        # merge adjacent cells
fred's avatar
fred committed
110
111
112
113
114
115
116
117
118
119
120
121
        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
122
            grid[i] = [x for x in grid[i] if x is not None]
fred's avatar
fred committed
123
124
125
126
127
128
129
130

        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
131
132
133
134
135
136
137
                    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
138
139
140
141
                        cell.h += 1
                except IndexError:
                    pass

fred's avatar
fred committed
142
143
144
145
        # cut night at 3am
        grid = grid[:42]
        times = times[:42]

fred's avatar
fred committed
146
        context['grid'] = grid
fred's avatar
fred committed
147
        context['times'] = times
148
149
        context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
                'Vendredi', 'Samedi', 'Dimanche']
fred's avatar
fred committed
150
151
152
153
154

        return context

grid = Grid.as_view()

155

fred's avatar
fred committed
156
157
158
class Home(TemplateView):
    template_name = 'home.html'

159
160
    def get_context_data(self, **kwargs):
        context = super(Home, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
161
        context['emissions'] = Emission.objects.filter(archived=False).order_by('?')
162
163
        return context

fred's avatar
fred committed
164
home = Home.as_view()
165
166
167
168
169
170
171
172
173
174

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
175

176
177
class WhatsOnAir(TemplateView):
    template_name = 'whatsonair.html'
Simon Daron's avatar
Simon Daron committed
178
    def get_context_data(self, **kwargs):
179
        context = super(WhatsOnAir, self).get_context_data(**kwargs)
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
        now = datetime.now()
        date_start = now - timedelta(days=1)
        date_end = now + timedelta(days=1)
        diffusions = Diffusion.objects.filter(
                datetime__range=(date_start, date_end)).order_by('datetime')
        diffusions = [x for x in diffusions if x.datetime <= now and
                        now <= x.datetime + timedelta(minutes=x.episode.emission.duration)]

        episode = None
        emission = None
        if diffusions: # there should be only one
            diffusion = diffusions[0]
            episode = diffusion.episode
            emission = episode.emission
        else:
            for schedule in Schedule.objects.all():
                if not schedule.matches(now):
                    continue
                emission = schedule.emission
                break

	context['episode'] = episode
	context['emission'] = emission
203
204
205
206
207
208
209
210
211
        return context

what = WhatsOnAir.as_view()

class Player(TemplateView):
    template_name = 'player.html'

    def get_context_data(self, **kwargs):
        context = super(Player, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
212
	#context['whatsonair'] = WhatsOnAir.as_view() #HOW TO PRELOAD WHATSONAIR ON PLAYER?
Simon Daron's avatar
Simon Daron committed
213
214
215
        return context

player = Player.as_view()
216
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