views.py 15.3 KB
Newer Older
fred's avatar
fred committed
1
import copy
fred's avatar
fred committed
2
import csv
fred's avatar
fred committed
3
import datetime
fred's avatar
fred committed
4
import os
5
import tempfile
fred's avatar
fred committed
6

fred's avatar
fred committed
7 8 9
import mutagen

from django.core.files.storage import default_storage
10
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
fred's avatar
fred committed
11
from django.core.urlresolvers import reverse
fred's avatar
fred committed
12
from django.contrib import messages
13
from django.db.models import Q
fred's avatar
fred committed
14
from django.http import HttpResponse, HttpResponseRedirect, FileResponse
fred's avatar
fred committed
15
from django.utils.six import StringIO
fred's avatar
fred committed
16
from django.utils.translation import ugettext_lazy as _
fred's avatar
fred committed
17
from django.views.generic.base import RedirectView, TemplateView
fred's avatar
fred committed
18
from django.views.generic.dates import DayArchiveView
fred's avatar
fred committed
19
from django.views.generic.detail import DetailView
fred's avatar
fred committed
20
from django.views.generic.edit import CreateView, FormView
fred's avatar
fred committed
21
from django.views.generic.list import ListView
fred's avatar
fred committed
22

23
from .forms import UploadTracksForm, TrackMetaForm, TrackSearchForm, CleanupForm
24
from .models import (SomaLogLine, Track, Artist, NonstopFile, ScheduledDiffusion, Jingle,
25
        Stream, LOCAL_BASE_PATH)
26 27 28 29
from emissions.models import Nonstop, Diffusion

from . import utils

fred's avatar
fred committed
30 31 32 33 34 35

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


fred's avatar
fred committed
39 40 41 42 43 44 45
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'),
fred's avatar
fred committed
46 47 48
                    line.filepath.short,
                    line.filepath.track.title,
                    line.filepath.track.artist.name,
fred's avatar
fred committed
49 50
                    line.filepath.track.language,
                    line.filepath.track.instru and 'instru' or '',
51
                    line.filepath.track.cfwb and 'cfwb' or '',
52
                    line.filepath.track.added_to_nonstop_timestamp.strftime('%Y-%m-%d %H:%M') if line.filepath.track.added_to_nonstop_timestamp else '',
53
                    ])
fred's avatar
fred committed
54 55
            else:
                writer.writerow([line.play_timestamp.strftime('%Y-%m-%d %H:%M'),
fred's avatar
fred committed
56
                                line.filepath.short])
57
        return HttpResponse(out.getvalue(), content_type='text/csv; charset=utf-8')
fred's avatar
fred committed
58 59


fred's avatar
fred committed
60 61 62 63 64 65 66
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
67 68 69 70


class TrackDetailView(DetailView):
    model = Track
fred's avatar
fred committed
71

fred's avatar
fred committed
72 73
    def get_context_data(self, **kwargs):
        ctx = super(TrackDetailView, self).get_context_data(**kwargs)
74
        ctx['metadata_form'] = TrackMetaForm(instance=self.object)
fred's avatar
fred committed
75 76 77
        return ctx

    def post(self, request, *args, **kwargs):
fred's avatar
fred committed
78
        assert self.request.user.has_perm('nonstop.add_track')
fred's avatar
fred committed
79 80
        instance = self.get_object()
        old_nonstop_zones = copy.copy(instance.nonstop_zones.all())
81 82
        form = TrackMetaForm(request.POST, instance=instance)
        form.save()
fred's avatar
fred committed
83 84 85 86 87
        new_nonstop_zones = self.get_object().nonstop_zones.all()
        if set(old_nonstop_zones) != set(new_nonstop_zones):
            instance.sync_nonstop_zones()
        return HttpResponseRedirect('.')

fred's avatar
fred committed
88 89 90

class ArtistDetailView(DetailView):
    model = Artist
fred's avatar
fred committed
91 92 93 94


class ArtistListView(ListView):
    model = Artist
fred's avatar
fred committed
95 96 97


class ZoneStats(object):
98
    def __init__(self, zone, from_date=None, until_date=None, **kwargs):
fred's avatar
fred committed
99
        self.zone = zone
100 101 102 103 104 105 106
        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
107 108

    def count(self, **kwargs):
109
        return self.qs.filter(**kwargs).count()
fred's avatar
fred committed
110 111 112 113 114

    def percentage(self, **kwargs):
        total = self.count()
        if total == 0:
            return '-'
fred's avatar
fred committed
115
        return '%.2f%%' % (100. * self.count(**kwargs) / total)
fred's avatar
fred committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

    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
135 136 137 138 139 140 141
    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
142
        return '%.2f%%' % (100. * self.french() / considered_tracks)
fred's avatar
fred committed
143

144 145 146 147 148 149 150 151 152 153 154 155
    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
156 157 158 159 160 161
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')
162 163 164 165 166 167 168 169
        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
170
        for zone in context['zones']:
171
            zone.stats = ZoneStats(zone, **kwargs)
fred's avatar
fred committed
172
        return context
fred's avatar
fred committed
173 174 175 176 177 178 179 180


class UploadTracksView(FormView):
    form_class = UploadTracksForm
    template_name = 'nonstop/upload.html'
    success_url = '.'

    def post(self, request, *args, **kwargs):
fred's avatar
fred committed
181
        assert self.request.user.has_perm('nonstop.add_track')
fred's avatar
fred committed
182 183 184 185 186 187 188 189
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        tracks = request.FILES.getlist('tracks')
        if not form.is_valid():
            return self.form_invalid(form)
        missing_metadata = []
        metadatas = {}
        for f in tracks:
190 191 192 193
            with tempfile.NamedTemporaryFile(prefix='track-upload') as tmpfile:
                tmpfile.write(f.read())
                f.seek(0)
                metadata = mutagen.File(tmpfile.name, easy=True)
fred's avatar
fred committed
194 195 196 197 198 199 200 201 202
            if not metadata or not metadata.get('artist') or not metadata.get('title'):
                missing_metadata.append(f.name)
            else:
                metadatas[f.name] = metadata
        if missing_metadata:
            form.add_error('tracks', _('Missing metadata in: ') + ', '.join(missing_metadata))
            return self.form_invalid(form)

        for f in tracks:
fred's avatar
fred committed
203 204 205 206
            metadata = metadatas[f.name]
            artist_name = metadata.get('artist')[0]
            track_title = metadata.get('title')[0]

fred's avatar
fred committed
207
            monthdir = datetime.datetime.today().strftime('%Y-%m')
fred's avatar
fred committed
208
            filepath = '%s/%s - %s - %s%s' % (monthdir,
fred's avatar
fred committed
209 210 211
                datetime.datetime.today().strftime('%y%m%d'),
                artist_name[:50].replace('/', ' ').strip(),
                track_title[:80].replace('/', ' ').strip(),
fred's avatar
fred committed
212
                os.path.splitext(f.name)[-1])
fred's avatar
fred committed
213 214

            artist, created = Artist.objects.get_or_create(name=artist_name)
fred's avatar
fred committed
215 216
            track, created = Track.objects.get_or_create(title=track_title, artist=artist,
                    defaults={'uploader': self.request.user})
217 218 219 220
            if created or not track.file_exists():
                default_storage.save(os.path.join('nonstop', 'tracks', filepath), content=f)
                nonstop_file = NonstopFile()
                nonstop_file.set_track_filepath(filepath)
221 222 223
                nonstop_file.track = track
                nonstop_file.save()
            else:
224 225
                # don't keep duplicated file and do not create a duplicated nonstop file object
                pass
fred's avatar
fred committed
226 227 228
            if request.POST.get('nonstop_zone'):
                track.nonstop_zones.add(
                        Nonstop.objects.get(id=request.POST.get('nonstop_zone')))
229
            track.sync_nonstop_zones()
fred's avatar
fred committed
230 231 232

        messages.info(self.request, '%d new track(s)' % len(tracks))
        return self.form_valid(form)
233 234 235 236 237 238


class RecentTracksView(ListView):
    template_name = 'nonstop/recent_tracks.html'

    def get_queryset(self):
fred's avatar
fred committed
239
        return Track.objects.exclude(creation_timestamp__isnull=True).order_by('-creation_timestamp')[:50]
240 241

    def post(self, request, *args, **kwargs):
fred's avatar
fred committed
242
        assert self.request.user.has_perm('nonstop.add_track')
243 244 245 246 247 248 249 250
        for track_id in request.POST.getlist('track'):
            track = Track.objects.get(id=track_id)
            track.language = request.POST.get('lang-%s' % track_id, '')
            track.instru = 'instru-%s' % track_id in request.POST
            track.sabam = 'sabam-%s' % track_id in request.POST
            track.cfwb = 'cfwb-%s' % track_id in request.POST
            track.save()
        return HttpResponseRedirect('.')
fred's avatar
fred committed
251 252 253 254


class QuickLinksView(TemplateView):
    template_name = 'nonstop/quick_links.html'
fred's avatar
fred committed
255 256 257 258 259


class SearchView(TemplateView):
    template_name = 'nonstop/search.html'

260
    def get_queryset(self):
261 262
        queryset = Track.objects.all()

fred's avatar
fred committed
263 264
        q = self.request.GET.get('q')
        if q:
265 266 267 268 269
            queryset = queryset.filter(Q(title__icontains=q.lower()) | Q(artist__name__icontains=q.lower()))

        zone = self.request.GET.get('zone')
        if zone:
            from emissions.models import Nonstop
270 271
            if zone == 'none':
                queryset = queryset.filter(nonstop_zones=None)
fred's avatar
fred committed
272 273
            elif zone == 'any':
                queryset = queryset.filter(nonstop_zones__isnull=False).distinct()
274 275 276 277 278 279 280 281
            else:
                queryset = queryset.filter(nonstop_zones=zone)

        order = self.request.GET.get('order_by') or 'title'
        if order:
            if 'added_to_nonstop_timestamp' in order:
                queryset = queryset.filter(added_to_nonstop_timestamp__isnull=False)
            queryset = queryset.order_by(order)
282 283 284 285 286 287 288 289 290
        return queryset

    def get_context_data(self, **kwargs):
        ctx = super(SearchView, self).get_context_data(**kwargs)
        ctx['form'] = TrackSearchForm(self.request.GET)
        queryset = self.get_queryset()
        qs = self.request.GET.copy()
        qs.pop('page', None)
        ctx['qs'] = qs.urlencode()
291 292 293 294 295 296 297 298 299 300

        tracks = Paginator(queryset.select_related(), 20)

        page = self.request.GET.get('page')
        try:
            ctx['tracks'] = tracks.page(page)
        except PageNotAnInteger:
            ctx['tracks'] = tracks.page(1)
        except EmptyPage:
            ctx['tracks'] = tracks.page(tracks.num_pages)
301

fred's avatar
fred committed
302
        return ctx
303 304


305 306 307 308
class SearchCsvView(SearchView):
    def get(self, request, *args, **kwargs):
        out = StringIO()
        writer = csv.writer(out)
309
        writer.writerow(['Title', 'Artist', 'Zones', 'Language', 'Instru', 'CFWB', 'Ajout'])
310 311
        for track in self.get_queryset():
            writer.writerow([
fred's avatar
fred committed
312 313 314
                track.title if track.title else 'Inconnu',
                track.artist.name if (track.artist and track.artist.name) else 'Inconnu',
                ' + '.join([x.title for x in track.nonstop_zones.all()]),
315 316
                track.language or '',
                track.instru and 'instru' or '',
317 318 319
                track.cfwb and 'cfwb' or '',
                track.added_to_nonstop_timestamp.strftime('%Y-%m-%d %H:%M') if track.added_to_nonstop_timestamp else '',
                ])
320 321 322
        return HttpResponse(out.getvalue(), content_type='text/csv; charset=utf-8')


323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
class CleanupView(TemplateView):
    template_name = 'nonstop/cleanup.html'

    def get_context_data(self, **kwargs):
        ctx = super(CleanupView, self).get_context_data(**kwargs)
        ctx['form'] = CleanupForm()

        zone = self.request.GET.get('zone')
        if zone:
            from emissions.models import Nonstop
            ctx['zone'] = Nonstop.objects.get(id=zone)
            ctx['count'] = Track.objects.filter(nonstop_zones=zone).count()
            ctx['tracks'] = Track.objects.filter(nonstop_zones=zone).order_by(
                            'added_to_nonstop_timestamp').select_related()[:30]
        return ctx

    def post(self, request, *args, **kwargs):
fred's avatar
fred committed
340
        assert self.request.user.has_perm('nonstop.add_track')
341 342 343 344 345 346 347 348 349 350
        count = 0
        for track_id in request.POST.getlist('track'):
            if request.POST.get('remove-%s' % track_id):
                track = Track.objects.get(id=track_id)
                track.nonstop_zones.clear()
                track.sync_nonstop_zones()
                count += 1
        if count:
            messages.info(self.request, 'Removed %d new track(s)' % count)
        return HttpResponseRedirect('.')
351 352


353
class AddSomaDiffusionView(CreateView):
354
    model = ScheduledDiffusion
fred's avatar
fred committed
355 356 357
    fields = ['jingle', 'stream']
    template_name = 'nonstop/streamed-diffusion.html'

358 359 360 361 362 363 364 365
    @property
    def fields(self):
        diffusion = Diffusion.objects.get(id=self.kwargs['pk'])
        fields = ['jingle']
        if not diffusion.episode.soundfile_set.filter(fragment=False).exists():
            fields.append('stream')
        return fields

fred's avatar
fred committed
366
    def get_initial(self):
367
        initial = super(AddSomaDiffusionView, self).get_initial()
368 369 370
        initial['jingle'] = None
        if 'stream' in self.fields:
            initial['jingle'] = Jingle.objects.filter(default_for_streams=True).first()
fred's avatar
fred committed
371
        initial['stream'] = Stream.objects.all().first()
fred's avatar
fred committed
372 373
        return initial

fred's avatar
fred committed
374 375
    def form_valid(self, form):
        form.instance.diffusion_id = self.kwargs['pk']
376
        episode = form.instance.diffusion.episode
377 378 379 380 381 382
        if 'stream' in self.fields and form.instance.stream_id is None:
            messages.error(self.request, _('missing stream'))
            return HttpResponseRedirect(reverse('episode-view', kwargs={
                'emission_slug': episode.emission.slug,
                'slug': episode.slug}))
        response = super(AddSomaDiffusionView, self).form_valid(form)
383
        messages.info(self.request, _('%s added to schedule') % episode.emission.title)
384 385 386 387 388
        return response

    def get_success_url(self):
        diffusion = Diffusion.objects.get(id=self.kwargs['pk'])
        episode = diffusion.episode
fred's avatar
fred committed
389 390 391
        return reverse('episode-view', kwargs={
            'emission_slug': episode.emission.slug,
            'slug': episode.slug})
fred's avatar
fred committed
392 393


394
class DelSomaDiffusionView(RedirectView):
395
    def get_redirect_url(self, pk):
396
        soma_diffusion = ScheduledDiffusion.objects.filter(diffusion_id=pk).first()
397
        episode = soma_diffusion.episode
398
        ScheduledDiffusion.objects.filter(diffusion_id=pk).update(diffusion_id=None)
fred's avatar
fred committed
399
        messages.info(self.request, _('%s removed from schedule') % episode.emission.title)
fred's avatar
fred committed
400 401 402 403 404
        return reverse('episode-view', kwargs={
            'emission_slug': episode.emission.slug,
            'slug': episode.slug})


fred's avatar
fred committed
405 406 407
def jingle_audio_view(request, *args, **kwargs):
    jingle = Jingle.objects.get(id=kwargs['pk'])
    return FileResponse(open(os.path.join(LOCAL_BASE_PATH, 'SPOTS', jingle.filepath), 'rb'))