paniktags.py 7.38 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 urlparse
fred's avatar
fred committed
6
import urllib2
7
8
import uuid

fred's avatar
fred committed
9
from django import template
10
from django.conf import settings
Simon Daron's avatar
Simon Daron committed
11
12
from django.db.models.query import QuerySet
from django.utils import simplejson
Simon Daron's avatar
Simon Daron committed
13
14
from datetime import datetime, timedelta

fred's avatar
fred committed
15
from emissions.models import Emission, Episode, NewsItem
Simon Daron's avatar
Simon Daron committed
16
from emissions.utils import period_program
fred's avatar
fred committed
17

fred's avatar
fred committed
18
from panikweb import utils
19
from panikweb import search
fred's avatar
fred committed
20

fred's avatar
fred committed
21
22
23
24
register = template.Library()

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

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

Simon Daron's avatar
Simon Daron committed
34
35
36
37
38
39
40
@register.inclusion_tag('listen/nav.html', takes_context=True)
def listen_nav(context, date=None, klass=None):
    return {
        'class': klass,
        'categories': context.get('categories'),
    }

41
@register.inclusion_tag('news/nav.html', takes_context=True)
42
def news_nav(context, date=None, klass=None):
43
    return {
44
        'class': klass,
45
        'newsitem': context.get('newsitem'),
Simon Daron's avatar
Simon Daron committed
46
        'categories': context.get('categories'),
47
48
49
        'news': context.get('news'),
    }

Simon Daron's avatar
Simon Daron committed
50
@register.inclusion_tag('emissions/nav.html', takes_context=True)
Simon Daron's avatar
Simon Daron committed
51
def emission_nav(context, date=None, klass=None):
Simon Daron's avatar
Simon Daron committed
52
    return {
Simon Daron's avatar
Simon Daron committed
53
54
        'class': klass,
        'categories': context.get('categories'),
55
        'episodes': context.get('episodes'),
Simon Daron's avatar
Simon Daron committed
56
57
58
59
        'emission': context.get('emission'),
        'episode': context.get('episode'),
    }

60
@register.inclusion_tag('episodes/resume.html', takes_context=True)
61
def episode_resume(context, date=None, model=None, klass=None):
62
    return {
63
        'model': model,
64
        'class': klass,
65
66
67
68
        'episode': context.get('episode'),
        'date': date,
    }

69
70
71
72
73
74
75
76
@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'),
    }

77
78
79
80
81
82
83
@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
84
85
86
87
88
89
90
@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
91
92
93
94
95
96
97
@register.inclusion_tag('emissions/inline.html', takes_context=True)
def emission_inline(context, date=None):
    return {
        'emission': context.get('emission'),
        'schedules': context.get('schedules'),
    }

98
@register.inclusion_tag('soundfiles/resume.html')
fred's avatar
fred committed
99
100
101
def soundfile_resume(soundfile, date=None):
    return {'soundfile': soundfile,
            'date': date}
102

103
104
105
@register.inclusion_tag('includes/player.html', takes_context=False)
def player():
    return {'unique': uuid.uuid4()}
106

107
108
109
110
111
@register.inclusion_tag('includes/metaNav.html', takes_context=True)
def metanav(context, active=None):
    return {
        'sectionName': context.get('sectionName')
	}
112

Simon Daron's avatar
Simon Daron committed
113
@register.inclusion_tag('includes/week.html', takes_context=True)
fred's avatar
fred committed
114
115
116
def weekview(context, year=None, week=None, weekday=None, fragment=None):
    year = year if year else datetime.today().isocalendar()[0]
    week = week if week else datetime.today().isocalendar()[1]
117
    weekday = weekday if weekday else datetime.today().weekday()
fred's avatar
fred committed
118
119

    date = utils.tofirstdayinisoweek(year, week)
Simon Daron's avatar
Simon Daron committed
120
121
122
123
124
125
126
127
128
129
    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,
130
        'weekday': weekday,
Simon Daron's avatar
Simon Daron committed
131
132
133
134
        'week': week,
        'year': year,
    }

Simon Daron's avatar
Simon Daron committed
135
136
@register.inclusion_tag('news/inline.html', takes_context=True)
def news_inline(context, klass=None, logo=None):
137
    return {
Simon Daron's avatar
Simon Daron committed
138
            'content': context.get('content'),
139
140
141
            'class': klass,
            'logo': logo
    }
fred's avatar
fred committed
142

Simon Daron's avatar
Simon Daron committed
143
144
145
@register.inclusion_tag('news/roll.html', takes_context=True)
def newsroll(context, nbr=None):
    return {
Simon Daron's avatar
Simon Daron committed
146
        'categories': context.get('categories'),
Simon Daron's avatar
Simon Daron committed
147
148
149
150
151
        'news': context.get('news'),
        'focus': context.get('focus'),
        'nbr': nbr,
    }

fred's avatar
fred committed
152

Simon Daron's avatar
Simon Daron committed
153
154
155
156
157
158
@register.filter
def jsonify(object):
    if isinstance(object, QuerySet):
        return serialize('json', object)
    return simplejson.dumps(object)

Simon Daron's avatar
Simon Daron committed
159
160
161
162
163
164
165
166
167
168
169
170
171
@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
172
173
174
175
176
177
178
@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):
fred's avatar
fred committed
179
180
181
182
183
184
185
186
    scheme, netloc, path, query, fragment = list(urlparse.urlsplit(str(url)))
    facet = 'categories_exact:%s' % facet.encode('utf-8')
    query_string = urlparse.parse_qsl(query)
    query_string = [x for x in query_string if not (
        x[0] == 'selected_facets' and x[1] == facet)]
    query = '&'.join(['%s=%s' % x for x in query_string])
    url = urlparse.urlunsplit([scheme, netloc, path, query, None])
    return re.sub(r'&page=\d+', '', url)
fred's avatar
fred committed
187
188
189
190

@register.filter
def append_tag_facet(url, facet):
    facet = urllib2.quote(facet.encode('utf-8'), safe='')
fred's avatar
fred committed
191
192
    if not '?' in url:
        url = url + '?'
fred's avatar
fred committed
193
194
195
196
197
    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='')
fred's avatar
fred committed
198
199
    if not '?' in url:
        url = url + '?'
fred's avatar
fred committed
200
    return re.sub(r'&page=\d+', '', url + '&selected_facets=categories_exact:%s' % facet)
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224


@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))
225
226
227
228
229


@register.inclusion_tag('includes/piwik.html')
def piwik():
    return {'enabled': settings.ENABLE_PIWIK}
fred's avatar
fred committed
230
231
232
233
234
235
236


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

@register.inclusion_tag('includes/related.html', takes_context=False)
def related_objects(object):
fred's avatar
fred committed
240
    sqs = search.MoreLikeThisSearchQuerySet().models(Emission, Episode, NewsItem)
241
    return {'more_like_this': sqs.more_like_this(object)[:12]}