Thumbnail fixes.
[audio.git] / src / youtube / views.py
1 from django.contrib.auth.decorators import permission_required
2 from django.http import HttpResponse
3 from django.shortcuts import redirect, get_object_or_404
4 from django.urls import reverse
5 from django.utils.decorators import method_decorator
6 from django.utils.timezone import now
7 from django.views import View
8 from django.views.decorators.http import require_POST
9 from django.views.generic import DetailView
10 from django.views.generic.detail import SingleObjectMixin
11 from archive.constants import status
12 from archive.models import Audiobook
13 from . import models, tasks
14
15
16
17 @require_POST
18 @permission_required('archive.change_audiobook')
19 def publish(request, aid, publish=True):
20     audiobook = get_object_or_404(Audiobook, id=aid)
21     if audiobook.is_youtube_publishable:
22         audiobook.youtube_status = status.QUEUED
23         audiobook.youtube_queued = now()
24         audiobook.save(update_fields=['youtube_status', 'youtube_queued'])
25     return redirect(reverse('file', args=[aid]))
26
27
28 def thumbnail(request, aid, thumbnail_id=None):
29     audiobook = get_object_or_404(Audiobook, id=aid)
30     if thumbnail_id is None:
31         yt = models.YouTube.objects.first()
32         buf = yt.prepare_thumbnail(audiobook)
33     else:
34         template = get_object_or_404(models.ThumbnailTemplate, id=thumbnail_id)
35         buf = template.generate(audiobook)
36     buf = buf.getvalue() if buf is not None else b''
37     return HttpResponse(buf, content_type='image/png')
38
39
40 class Preview(DetailView):
41     model = Audiobook
42     template_name = 'youtube/preview.html'
43
44     def get_context_data(self, **kwargs):
45         ctx = super().get_context_data(**kwargs)
46         yt = models.YouTube.objects.first()
47         ctx['data'] = yt.get_data(ctx['object'])
48         ctx['title'] = yt.get_title(ctx['object'])
49         ctx['description'] = yt.get_description(ctx['object'])
50         ctx['templates'] = models.ThumbnailTemplate.objects.all()
51         return ctx
52
53
54 @method_decorator(permission_required('archive.change_audiobook'), name='dispatch')
55 class Update(SingleObjectMixin, View):
56     model = Audiobook
57
58     def post(self, request, pk):
59         yt = models.YouTube.objects.first()
60         yt.update_data(self.get_object())
61         return redirect(reverse('file', args=[pk]))
62
63
64 @method_decorator(permission_required('archive.change_audiobook'), name='dispatch')
65 class UpdateThumbnail(SingleObjectMixin, View):
66     model = Audiobook
67
68     def post(self, request, pk):
69         yt = models.YouTube.objects.first()
70         yt.update_thumbnail(self.get_object())
71         return redirect(reverse('file', args=[pk]))