views.py 8.24 KB
Newer Older
1 2
import datetime

fred's avatar
fred committed
3
from django.contrib.auth.decorators import login_required
4 5
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
6
from django.template import loader, Context
7
from django.views.generic.base import TemplateView, RedirectView
fred's avatar
fred committed
8
from django.views.generic.list import ListView
9
from django.contrib import messages
fred's avatar
fred committed
10
from django.shortcuts import redirect
fred's avatar
fred committed
11

12
from emissions.models import *
13
from emissions.utils import period_program
fred's avatar
fred committed
14 15
from panikombo.models import Topik
from combo.data.models import Page
fred's avatar
fred committed
16

17
import emissions.views
18
import newsletter.views
19

fred's avatar
fred committed
20 21
from .poll.models import Vote

fred's avatar
fred committed
22 23 24 25 26
class Home(TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super(Home, self).get_context_data(**kwargs)
fred's avatar
fred committed
27 28 29 30
        try:
            vote = Vote.objects.get(user=self.request.user)
        except Vote.DoesNotExist:
            context['display_poll_button'] = True
31
        context['emissions'] = self.request.user.emissions.all().order_by('title')
fred's avatar
fred committed
32
        context['news_categories'] = self.request.user.news_categories.all().order_by('title')
33
        if self.request.user.has_perm('emissions.add_focus'):
34
            context['focused_items'] = Focus.objects.select_related().filter(current=True)
35 36
            context['recent_episodes'] = Episode.objects.select_related(
                    ).order_by('-last_update_timestamp')
37 38 39 40
            context['recent_newsitems'] = NewsItem.objects.select_related(
                    ).order_by('-last_update_timestamp')
            context['recent_soundfiles'] = SoundFile.objects.select_related(
                    ).order_by('-last_update_timestamp')
41

fred's avatar
fred committed
42 43 44
        return context

home = login_required(Home.as_view())
45 46 47 48 49


class EmissionListView(emissions.views.EmissionListView):
    pass

50
emissions_list = login_required(EmissionListView.as_view())
fred's avatar
fred committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65



class NewsListView(ListView):
    model = NewsCategory

    def get_queryset(self):
        return NewsCategory.objects.order_by('title')

    def get_context_data(self, **kwargs):
        context = super(NewsListView, self).get_context_data(**kwargs)
        context['unsorted_newsitems'] = NewsItem.objects.filter(category__isnull=True).order_by('title')
        return context

news = login_required(NewsListView.as_view())
66 67 68 69 70 71 72


class NewsletterCreateView(newsletter.views.NewsletterCreateView):
    def get_initial(self):
        initial = super(NewsletterCreateView, self).get_initial()

        newsletter_body = loader.get_template('newsletter/body.html')
73
        newsletter_subject = loader.get_template('newsletter/subject.txt')
74 75 76 77 78 79 80
        context = Context()

        date = datetime.datetime.today()
        if date.weekday() > 0:
            date = date + datetime.timedelta(days=7-date.weekday())

        date = datetime.datetime(*date.timetuple()[:3])
81
        date_end = date + datetime.timedelta(days=7)
82 83

        context['date'] = date
84
        context['date_end'] = date_end
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

        context['soundfiles'] = SoundFile.objects.filter(
                podcastable=True, fragment=False).select_related().filter(
                        creation_timestamp__gte=date-datetime.timedelta(days=7))

        context['diffusions'] = list(Diffusion.objects.select_related().filter(
                datetime__gte=date,
                datetime__lte=date+datetime.timedelta(days=7)).order_by('datetime'))

        # remove rebroadcasts made during the same week
        seen_episodes = {}
        for diff in context['diffusions'][:]:
            if diff.episode.id in seen_episodes:
                context['diffusions'].remove(diff)
            seen_episodes[diff.episode.id] = True

101
        initial['subject'] = newsletter_subject.render(context)
102 103 104 105
        initial['text'] = newsletter_body.render(context)
        return initial

newsletter_create = NewsletterCreateView.as_view()
106 107 108 109 110 111 112 113


class FocusSetView(RedirectView):
    permanent = False

    def get_redirect_url(self, object_type, object_id):
        if not self.request.user.has_perm('emissions.add_focus'):
            raise PermissionDenied()
114
        messages.success(self.request, emissions.views.SUCCESS_MESSAGE)
115 116
        if object_type == 'emission':
            emission = Emission.objects.get(id=object_id)
fred's avatar
fred committed
117 118 119 120 121
            try:
                f = Focus.objects.get(emission=emission)
            except Focus.DoesNotExist:
                f = Focus()
            f.current = True
122 123 124 125 126
            f.emission = emission
            f.save()
            return reverse('emission-view', kwargs={'slug': emission.slug})
        if object_type == 'episode':
            episode = Episode.objects.get(id=object_id)
fred's avatar
fred committed
127 128 129 130 131
            try:
                f = Focus.objects.get(episode=episode)
            except Focus.DoesNotExist:
                f = Focus()
            f.current = True
132 133 134 135 136 137
            f.episode = episode
            f.save()
            return reverse('episode-view', kwargs={
                'emission_slug': episode.emission.slug, 'slug': episode.slug})
        if object_type == 'newsitem':
            newsitem = NewsItem.objects.get(id=object_id)
fred's avatar
fred committed
138 139 140 141 142
            try:
                f = Focus.objects.get(newsitem=newsitem)
            except Focus.DoesNotExist:
                f = Focus()
            f.current = True
143 144 145 146 147
            f.newsitem = newsitem
            f.save()
            return reverse('newsitem-view', kwargs={'slug': newsitem.slug})
        if object_type == 'soundfile':
            soundfile = SoundFile.objects.get(id=object_id)
fred's avatar
fred committed
148 149 150 151 152
            try:
                f = Focus.objects.get(soundfile=soundfile)
            except Focus.DoesNotExist:
                f = Focus()
            f.current = True
153 154 155 156 157 158
            f.soundfile = soundfile
            f.save()
            return reverse('episode-view', kwargs={
                'slug': soundfile.episode.slug,
                'emission_slug': soundfile.episode.emission.slug,
                })
fred's avatar
fred committed
159 160 161 162 163 164 165 166 167 168
        if object_type == 'page':
            page = Page.objects.get(id=object_id)
            try:
                f = Focus.objects.get(page=page)
            except Focus.DoesNotExist:
                f = Focus()
            f.current = True
            f.page = page
            f.save()
            return reverse('combo-manager-page-view', kwargs={'pk': object_id})
169 170 171 172 173 174 175 176 177 178

focus_set = FocusSetView.as_view()


class FocusUnsetView(RedirectView):
    permanent = False

    def get_redirect_url(self, object_type, object_id):
        if not self.request.user.has_perm('emissions.delete_focus'):
            raise PermissionDenied()
179
        messages.success(self.request, emissions.views.SUCCESS_MESSAGE)
180 181
        if object_type == 'emission':
            emission = Emission.objects.get(id=object_id)
fred's avatar
fred committed
182 183 184
            focus = Focus.objects.get(emission=emission)
            focus.current = False
            focus.save()
185 186 187
            return reverse('emission-view', kwargs={'slug': emission.slug})
        if object_type == 'episode':
            episode = Episode.objects.get(id=object_id)
fred's avatar
fred committed
188 189 190
            focus = Focus.objects.get(episode=episode)
            focus.current = False
            focus.save()
191 192 193 194
            return reverse('episode-view', kwargs={
                'emission_slug': episode.emission.slug, 'slug': episode.slug})
        if object_type == 'newsitem':
            newsitem = NewsItem.objects.get(id=object_id)
fred's avatar
fred committed
195 196 197
            focus = Focus.objects.get(newsitem=newsitem)
            focus.current = False
            focus.save()
198 199 200
            return reverse('newsitem-view', kwargs={'slug': newsitem.slug})
        if object_type == 'soundfile':
            soundfile = SoundFile.objects.get(id=object_id)
fred's avatar
fred committed
201 202 203
            focus = Focus.objects.get(soundfile=soundfile)
            focus.current = False
            focus.save()
204 205 206 207
            return reverse('episode-view', kwargs={
                'slug': soundfile.episode.slug,
                'emission_slug': soundfile.episode.emission.slug,
                })
fred's avatar
fred committed
208 209 210 211 212
        if object_type == 'page':
            focus = Focus.objects.get(page=object_id)
            focus.current = False
            focus.save()
            return reverse('combo-manager-page-view', kwargs={'pk': object_id})
213 214

focus_unset = FocusUnsetView.as_view()
fred's avatar
fred committed
215 216 217 218 219 220 221

def make_topik(request, page_pk):
    if Topik.objects.filter(page__id=page_pk).count():
        raise Exception('page already associated to topik')
    topik = Topik(page_id=page_pk)
    topik.save()
    return redirect('combo-manager-page-view', pk=page_pk)