Commit b580e11f authored by Simon Daron's avatar Simon Daron

add views.py

parent 4a50115c
from datetime import datetime, timedelta
import math, uuid
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from django.views.decorators.csrf import csrf_exempt
from jsonresponse import to_json
from emissions.models import Emission, Episode, Diffusion, SoundFile, \
Schedule, Nonstop, NewsItem, NewsCategory
from emissions.utils import whatsonair
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)],
'datetime': datetime(2007, 1, day+1)})
context['days'] = days
return context
program = ProgramView.as_view()
class TimeCell:
emissions = None
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)
schedules = Schedule.objects.all().order_by('datetime')
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])
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.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
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
grid[i] = [x for x in grid[i] if x is not None]
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:
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]
cell.h += 1
except IndexError:
pass
# cut night at 3am
grid = grid[:42]
times = times[:42]
context['grid'] = grid
context['times'] = times
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)
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['emissions'] = Emission.objects.filter(archived=False).order_by('title')
context['player'] = audioPlayer()
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)
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()
context['emissions'] = Emission.objects.filter(archived=False).order_by('?')
context['player'] = audioPlayer()
return context
news = News.as_view()
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)
context['player'] = audioPlayer()
return context
listen = Listen.as_view()
class audioPlayer:
def __init__(self):
self.unique = uuid.uuid4()
@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
class NewsItemDetailView(DetailView):
model = NewsItem
newsitem = NewsItemDetailView.as_view()
......@@ -5,7 +5,7 @@
<span class="control icon-volume-up resymbol huge"></span>
<span class="label">&nbsp;en direct</span>
</button>
<div id="WhatsOnAir"><strong>Unknown (Probably Non-Stop)<strong></div>
<div id="WhatsOnAir"></div>
<audio
id="DirectStreamPanik"
preload="none"
......@@ -35,18 +35,18 @@
var timer = null,
interval = 5000;
$('#WhatsOnAir').on('load',function(){
var self = $(this);
var WhatsOnAir = $(this);
$.getJSON('/onair.json', function(onair) {
self.fadeOut();
WhatsOnAir.fadeOut();
if(onair.data.episode || onair.data.emission){
var result = '';
result = result + ($.type(onair.data.emission) == 'object'?'<strong>'+onair.data.emission.title+'<strong>&nbsp;':'');
result = result + ($.type(onair.data.episode) == 'object'?'<span>'+onair.data.episode.title+'<span>':'');
self.html(result);
result = result + ($.type(onair.data.emission) == 'object'?'<strong>'+onair.data.emission.title+'</strong>&nbsp;':'');
result = result + ($.type(onair.data.episode) == 'object'?'<span>'+onair.data.episode.title+'</span>':'');
WhatsOnAir.html(result);
}
else{self.html('<strong>Unknown (Probably Non-Stop)</strong>');}
self.fadeIn();
}).error(function(msg) { });
else{WhatsOnAir.html('<strong>Unknown (Probably Non-Stop)</strong>');}
WhatsOnAir.fadeIn();
});
}).trigger('load');
$('#RefreshWhatsOnAir').on('activate',function(e){
$(this).addClass('spinning');
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment