views.py 4.65 KB
Newer Older
fred's avatar
fred committed
1
import csv
fred's avatar
fred committed
2
import datetime
fred's avatar
fred committed
3
from cStringIO import StringIO
fred's avatar
fred committed
4 5

from django.core.urlresolvers import reverse
fred's avatar
fred committed
6
from django.http import HttpResponse
fred's avatar
fred committed
7
from django.views.generic.base import RedirectView, TemplateView
fred's avatar
fred committed
8
from django.views.generic.dates import DayArchiveView
fred's avatar
fred committed
9
from django.views.generic.detail import DetailView
fred's avatar
fred committed
10
from django.views.generic.list import ListView
fred's avatar
fred committed
11

fred's avatar
fred committed
12
from .models import SomaLogLine, Track, Artist
fred's avatar
fred committed
13
from emissions.models import Nonstop
fred's avatar
fred committed
14 15 16 17 18 19

class SomaDayArchiveView(DayArchiveView):
    queryset = SomaLogLine.objects.all()
    date_field = "play_timestamp"
    make_object_list = True
    allow_future = False
fred's avatar
fred committed
20 21 22
    month_format = '%m'


fred's avatar
fred committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
class SomaDayArchiveCsvView(SomaDayArchiveView):
    def render_to_response(self, context, **response_kwargs):
        out = StringIO()
        writer = csv.writer(out)
        for line in context['object_list']:
            if line.filepath.track:
                writer.writerow([line.play_timestamp.strftime('%Y-%m-%d %H:%M'),
                    line.filepath.short.encode('utf-8', 'replace'),
                    line.filepath.track.title.encode('utf-8', 'replace'),
                    line.filepath.track.artist.name.encode('utf-8', 'replace'),
                    line.filepath.track.language,
                    line.filepath.track.instru and 'instru' or '',
                    line.filepath.track.cfwb and 'cfwb' or ''])
            else:
                writer.writerow([line.play_timestamp.strftime('%Y-%m-%d %H:%M'),
                                line.filepath.short.encode('utf-8', 'replace')])
39
        return HttpResponse(out.getvalue(), content_type='text/csv; charset=utf-8')
fred's avatar
fred committed
40 41


fred's avatar
fred committed
42 43 44 45 46 47 48
class RedirectTodayView(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        today = datetime.datetime.today()
        return reverse('archive_day', kwargs={
                        'year': today.year,
                        'month': today.month,
                        'day': today.day})
fred's avatar
fred committed
49 50 51 52


class TrackDetailView(DetailView):
    model = Track
fred's avatar
fred committed
53 54 55 56


class ArtistDetailView(DetailView):
    model = Artist
fred's avatar
fred committed
57 58 59 60


class ArtistListView(ListView):
    model = Artist
fred's avatar
fred committed
61 62 63


class ZoneStats(object):
64
    def __init__(self, zone, from_date=None, until_date=None, **kwargs):
fred's avatar
fred committed
65
        self.zone = zone
66 67 68 69 70 71 72
        self.qs = Track.objects.filter(nonstop_zones=self.zone, **kwargs)
        self.from_date = from_date
        if from_date:
            self.qs = self.qs.filter(nonstopfile__somalogline__play_timestamp__gte=from_date)
        if until_date:
            self.qs = self.qs.filter(nonstopfile__somalogline__play_timestamp__lte=until_date)
        self.qs = self.qs.distinct()
fred's avatar
fred committed
73 74

    def count(self, **kwargs):
75
        return self.qs.filter(**kwargs).count()
fred's avatar
fred committed
76 77 78 79 80

    def percentage(self, **kwargs):
        total = self.count()
        if total == 0:
            return '-'
fred's avatar
fred committed
81
        return '%.2f%%' % (100. * self.count(**kwargs) / total)
fred's avatar
fred committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

    def instru(self):
        return self.count(instru=True)

    def instru_percentage(self):
        return self.percentage(instru=True)

    def sabam(self):
        return self.count(sabam=True)

    def sabam_percentage(self):
        return self.percentage(sabam=True)

    def cfwb(self):
        return self.count(cfwb=True)

    def cfwb_percentage(self):
        return self.percentage(cfwb=True)

fred's avatar
fred committed
101 102 103 104 105 106 107
    def french(self):
        return self.count(language='fr')

    def french_percentage(self):
        considered_tracks = self.count() - self.instru()
        if considered_tracks == 0:
            return '-'
fred's avatar
fred committed
108
        return '%.2f%%' % (100. * self.french() / considered_tracks)
fred's avatar
fred committed
109

110 111 112 113 114 115 116 117 118 119 120 121
    def new_files(self):
        return self.count(nonstopfile__creation_timestamp__gte=self.from_date)

    def percent_new_files(self):
        return self.percentage(nonstopfile__creation_timestamp__gte=self.from_date)


def parse_date(date):
    if date.endswith('d'):
        return datetime.datetime.today() + datetime.timedelta(int(date.rstrip('d')))
    return datetime.datetime.strptime(date, '%Y-%m-%d').date()

fred's avatar
fred committed
122 123 124 125 126 127
class StatisticsView(TemplateView):
    template_name = 'nonstop/statistics.html'

    def get_context_data(self, **kwargs):
        context = super(StatisticsView, self).get_context_data(**kwargs)
        context['zones'] = Nonstop.objects.all().order_by('start')
128 129 130 131 132 133 134 135
        kwargs = {}
        if 'from' in self.request.GET:
            kwargs['from_date'] = parse_date(self.request.GET['from'])
            context['from_date'] = kwargs['from_date']
        if 'until' in self.request.GET:
            kwargs['until_date'] = parse_date(self.request.GET['until'])
        if 'onair' in self.request.GET:
            kwargs['nonstopfile__somalogline__on_air'] = True
fred's avatar
fred committed
136
        for zone in context['zones']:
137
            zone.stats = ZoneStats(zone, **kwargs)
fred's avatar
fred committed
138
        return context