paniktags.py 5.94 KB
Newer Older
fred's avatar
fred committed
1
2
import email.utils
import datetime
fred's avatar
fred committed
3
import re
fred's avatar
fred committed
4
import time
fred's avatar
fred committed
5
import urllib2
6
7
import uuid

fred's avatar
fred committed
8
from django import template
9
from django.conf import settings
Simon Daron's avatar
Simon Daron committed
10
11
from django.db.models.query import QuerySet
from django.utils import simplejson
Simon Daron's avatar
Simon Daron committed
12
13
14
15
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
16
17
18
19
20

register = template.Library()

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

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

30
31
32
33
34
35
36
@register.inclusion_tag('news/nav.html', takes_context=True)
def news_nav(context, date=None):
    return {
        'newsitem': context.get('newsitem'),
        'news': context.get('news'),
    }

Simon Daron's avatar
Simon Daron committed
37
@register.inclusion_tag('emissions/nav.html', takes_context=True)
Simon Daron's avatar
Simon Daron committed
38
def emission_nav(context, date=None, klass=None):
Simon Daron's avatar
Simon Daron committed
39
    return {
Simon Daron's avatar
Simon Daron committed
40
41
        'class': klass,
        'categories': context.get('categories'),
42
        'episodes': context.get('episodes'),
Simon Daron's avatar
Simon Daron committed
43
44
45
46
        'emission': context.get('emission'),
        'episode': context.get('episode'),
    }

47
@register.inclusion_tag('episodes/resume.html', takes_context=True)
48
def episode_resume(context, date=None, model=None, klass=None):
49
    return {
50
        'model': model,
51
        'class': klass,
52
53
54
55
        'episode': context.get('episode'),
        'date': date,
    }

56
57
58
59
60
61
62
63
@register.inclusion_tag('episodes/detail.html', takes_context=True)
def episode_detail(context, date=None):
    return {
        'episode': context.get('episode'),
        'emission': context.get('emission'),
        'diffusions': context.get('diffusions'),
    }

64
65
66
67
68
69
70
@register.inclusion_tag('emissions/detail.html', takes_context=True)
def emission_detail(context, date=None):
    return {
        'emission': context.get('emission'),
        'schedules': context.get('schedules'),
    }

Simon Daron's avatar
Simon Daron committed
71
72
73
74
75
76
77
@register.inclusion_tag('emissions/resume.html', takes_context=True)
def emission_resume(context, date=None):
    return {
        'emission': context.get('emission'),
        'schedules': context.get('schedules'),
    }

Simon Daron's avatar
Simon Daron committed
78
79
80
81
82
83
84
@register.inclusion_tag('emissions/inline.html', takes_context=True)
def emission_inline(context, date=None):
    return {
        'emission': context.get('emission'),
        'schedules': context.get('schedules'),
    }

85
86
87
@register.inclusion_tag('includes/player.html', takes_context=False)
def player():
    return {'unique': uuid.uuid4()}
88
89
90
91

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

Simon Daron's avatar
Simon Daron committed
93
@register.inclusion_tag('includes/week.html', takes_context=True)
94
95
96
97
98
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
99
100
101
102
103
104
105
106
107
108
    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,
109
        'weekday': weekday,
Simon Daron's avatar
Simon Daron committed
110
111
112
113
        'week': week,
        'year': year,
    }

114
115
116
117
118
119
120
@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
121
122


Simon Daron's avatar
Simon Daron committed
123
124
125
126
127
128
@register.filter
def jsonify(object):
    if isinstance(object, QuerySet):
        return serialize('json', object)
    return simplejson.dumps(object)

Simon Daron's avatar
Simon Daron committed
129
130
131
132
133
134
135
136
137
138
139
140
141
@register.filter
def strreplace ( string, args ): 
    find  = args.split(',')[0]
    replace = args.split(',')[1]
    return string.replace(find,replace)

@register.filter
def replace ( string, args ): 
    search  = args.split(args[0])[1]
    replace = args.split(args[0])[2]

    return re.sub( search, replace, string )

fred's avatar
fred committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
@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)
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185


@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))
186
187
188
189
190


@register.inclusion_tag('includes/piwik.html')
def piwik():
    return {'enabled': settings.ENABLE_PIWIK}
fred's avatar
fred committed
191
192
193
194
195
196
197


@register.filter
def rfc822(datetime):
    if datetime is None:
        return ''
    return email.utils.formatdate(time.mktime(datetime.timetuple()))