paniktags.py 4.32 KB
Newer Older
fred's avatar
fred committed
1
2
import re
import urllib2
3
4
import uuid

fred's avatar
fred committed
5
from django import template
Simon Daron's avatar
Simon Daron committed
6
7
from django.db.models.query import QuerySet
from django.utils import simplejson
Simon Daron's avatar
Simon Daron committed
8
9
10
11
from datetime import datetime, timedelta
from django.views.generic.dates import _date_from_string

from emissions.utils import period_program
fred's avatar
fred committed
12
13
14
15
16

register = template.Library()

@register.filter(name='zip')
def zip_lists(a, b):
fred's avatar
fred committed
17
    return zip(a, b)
18

Simon Daron's avatar
Simon Daron committed
19
20
@register.inclusion_tag('includes/audio.html', takes_context=True)
def audio(context, sound=None):
Simon Daron's avatar
Simon Daron committed
21
    return {
Simon Daron's avatar
Simon Daron committed
22
        'episode': context.get('episode'),
Simon Daron's avatar
Simon Daron committed
23
24
25
        'sound': sound
    }

Simon Daron's avatar
Simon Daron committed
26
27
28
@register.inclusion_tag('emissions/nav.html', takes_context=True)
def emission_nav(context, date=None):
    return {
29
        'episodes': context.get('episodes'),
Simon Daron's avatar
Simon Daron committed
30
31
32
33
        'emission': context.get('emission'),
        'episode': context.get('episode'),
    }

34
@register.inclusion_tag('episodes/resume.html', takes_context=True)
35
def episode_resume(context, date=None, model=None, klass=None):
36
    return {
37
        'model': model,
38
        'class': klass,
39
40
41
42
43
44
45
46
47
48
49
        'episode': context.get('episode'),
        'date': date,
    }

@register.inclusion_tag('emissions/detail.html', takes_context=True)
def emission_detail(context, date=None):
    return {
        'emission': context.get('emission'),
        'schedules': context.get('schedules'),
    }

50
51
52
@register.inclusion_tag('includes/player.html', takes_context=False)
def player():
    return {'unique': uuid.uuid4()}
53
54
55
56

@register.inclusion_tag('includes/metaNav.html', takes_context=False)
def metanav():
    return {}
57

Simon Daron's avatar
Simon Daron committed
58
@register.inclusion_tag('includes/week.html', takes_context=True)
59
60
61
62
63
def weekview(context, year=None, week=None, weekday=None, fragment= None):
    year = year if year else datetime.today().year
    week = week if week else datetime.today().isocalendar()[1]-1
    weekday = weekday if weekday else datetime.today().weekday()
    date = _date_from_string(str(year), '%Y', '1', '%w', str(week), '%W')
Simon Daron's avatar
Simon Daron committed
64
65
66
67
68
69
70
71
72
73
    date = datetime(*date.timetuple()[:3])

    program = period_program(date, date+timedelta(days=7))
    days = []
    for day in range(7):
        days.append({'cells': [x for x in program if x.is_on_weekday(day+1)],
                     'datetime': date+timedelta(days=day)})
    return {
        'fragment': fragment,
        'days': days,
74
        'weekday': weekday,
Simon Daron's avatar
Simon Daron committed
75
76
77
78
        'week': week,
        'year': year,
    }

79
80
81
82
83
84
85
@register.inclusion_tag('news/inline.html', takes_context=False)
def news_inline(content=None, klass=None, logo=None):
    return {
            'content': content,
            'class': klass,
            'logo': logo
    }
fred's avatar
fred committed
86
87


Simon Daron's avatar
Simon Daron committed
88
89
90
91
92
93
@register.filter
def jsonify(object):
    if isinstance(object, QuerySet):
        return serialize('json', object)
    return simplejson.dumps(object)

fred's avatar
fred committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
@register.filter
def remove_tag_facet(url, facet):
    facet = urllib2.quote(facet.encode('utf-8'), safe='')
    return re.sub(r'&page=\d+', '', url.replace('&selected_facets=tags_exact:%s' % facet, ''))

@register.filter
def remove_category_facet(url, facet):
    facet = urllib2.quote(facet.encode('utf-8'), safe='')
    return re.sub(r'&page=\d+', '', url.replace('&selected_facets=categories_exact:%s' % facet, ''))


@register.filter
def append_tag_facet(url, facet):
    facet = urllib2.quote(facet.encode('utf-8'), safe='')
    return re.sub(r'&page=\d+', '', url + '&selected_facets=tags_exact:%s' % facet)

@register.filter
def append_category_facet(url, facet):
    facet = urllib2.quote(facet.encode('utf-8'), safe='')
    return re.sub(r'&page=\d+', '', url + '&selected_facets=categories_exact:%s' % facet)
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137


@register.tag
def search_result_template(parser, token):
    try:
        tag_name, result_str = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("%r tag requires exactly one argument" % token.contents.split()[0])
    return FormatSearchResultNode(result_str)


class FormatSearchResultNode(template.Node):
    def __init__(self, result_str):
        self.result_var = template.Variable(result_str)

    def render(self, context):
        result = self.result_var.resolve(context)
        dir_mapping = {
            'newsitem': 'news',
            'emission': 'emissions',
            'episode': 'episodes'
        }
        t = template.loader.get_template('%s/search_result.html' % dir_mapping.get(result.model_name))
        return t.render(template.context.Context({'result': result}, autoescape=context.autoescape))