~widelands-dev/widelands-website/django_staticfiles

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import os.path
import random
import traceback
import json

from BeautifulSoup import BeautifulSoup
from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponse
from django.utils.functional import Promise
from django.utils.translation import check_for_language
from django.utils.encoding import force_unicode
from django import forms
from django.template.defaultfilters import urlize as django_urlize
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.conf import settings
from pybb import settings as pybb_settings


def render_to(template_path):
    """Expect the dict from view.

    Render returned dict with RequestContext.

    """

    def decorator(func):
        def wrapper(request, *args, **kwargs):
            import pdb
            #output = pdb.runcall(func, request, *args, **kwargs)
            output = func(request, *args, **kwargs)
            if not isinstance(output, dict):
                return output
            

            # TODO(Franku): 'MIME_TYPE' is never in output as i can see for now.
            # But if, this should maybe 'content_type' instead
            if 'MIME_TYPE' in output:
                kwargs['mimetype'] = output.pop('MIME_TYPE')
            if 'TEMPLATE' in output:
                template = output.pop('TEMPLATE')
            else:
                template = template_path

            return render(request, template, output)
        return wrapper

    return decorator


def paged(paged_list_name, per_page):  # , per_page_var='per_page'):
    """Parse page from GET data and pass it to view.

    Split the query set returned from view.

    """

    def decorator(func):
        def wrapper(request, *args, **kwargs):
            result = func(request, *args, **kwargs)
            if not isinstance(result, dict):
                return result
            try:
                page = int(request.GET.get('page', 1))
            except ValueError:
                page = 1

            real_per_page = per_page

            # if per_page_var:
            # try:
            #value = int(request.GET[per_page_var])
            # except (ValueError, KeyError):
            # pass
            # else:
            # if value > 0:
            #real_per_page = value

            from django.core.paginator import Paginator
            paginator = Paginator(result['paged_qs'], real_per_page)
            result[paged_list_name] = paginator.page(page).object_list
            result['page'] = page
            result['page_list'] = range(1, paginator.num_pages + 1)
            result['pages'] = paginator.num_pages
            result['per_page'] = real_per_page
            result['request'] = request
            return result
        return wrapper

    return decorator


def ajax(func):
    """Checks request.method is POST. Return error in JSON in other case.

    If view returned dict, returns JsonResponse with this dict as
    content.

    """
    def wrapper(request, *args, **kwargs):
        if request.method == 'POST':
            try:
                response = func(request, *args, **kwargs)
            except Exception, ex:
                response = {'error': traceback.format_exc()}
        else:
            response = {'error': {'type': 403,
                                  'message': 'Accepts only POST request'}}
        if isinstance(response, dict):
            return JsonResponse(response)
        else:
            return response
    return wrapper


class LazyJSONEncoder(json.JSONEncoder):
    """This fing need to save django from crashing."""

    def default(self, o):
        if isinstance(o, Promise):
            return force_unicode(o)
        else:
            return super(LazyJSONEncoder, self).default(o)


class JsonResponse(HttpResponse):
    """HttpResponse subclass that serialize data into JSON format."""
    # TODO(Franku): The mimetype argument maybe must be replaced with content_type

    def __init__(self, data, mimetype='application/json'):
        json_data = LazyJSONEncoder().encode(data)
        super(JsonResponse, self).__init__(
            content=json_data, content_type=mimetype)


def build_form(Form, _request, GET=False, *args, **kwargs):
    """Shorcut for building the form instance of given form class."""

    if not GET and 'POST' == _request.method:
        form = Form(_request.POST, _request.FILES, *args, **kwargs)
    elif GET and 'GET' == _request.method:
        form = Form(_request.GET, _request.FILES, *args, **kwargs)
    else:
        form = Form(*args, **kwargs)
    return form


def urlize(data):
    """Urlize plain text links in the HTML contents.

    Do not urlize content of A and CODE tags.

    """

    soup = BeautifulSoup(data)
    for chunk in soup.findAll(text=True):
        islink = False
        ptr = chunk.parent
        while ptr.parent:
            if ptr.name == 'a' or ptr.name == 'code':
                islink = True
                break
            ptr = ptr.parent
        if not islink:
            # Using unescape to prevent conversation of f.e. > to >
            chunk = chunk.replaceWith(django_urlize(unicode(unescape(chunk))))

    return unicode(soup)


def quote_text(text, user, markup):
    """Quote message using selected markup."""
    text = '*' + user.username + ' wrote:*\n\n' + text

    if markup == 'markdown':
        # Inserting a space after ">" will not change the generated HTML,
        # but it will unbreak certain constructs like '>:-))'.
        return '> ' + text.replace('\r', '').replace('\n', '\n> ') + '\n'
    elif markup == 'bbcode':
        return '[quote]\n%s\n[/quote]\n' % text
    else:
        return text


def absolute_url(path):
    return 'http://%s%s' % (pybb_settings.HOST, path)


def memoize_method(func):
    """Cached result of function call."""

    def wrapper(self, *args, **kwargs):
        CACHE_NAME = '__memcache'
        try:
            cache = getattr(self, CACHE_NAME)
        except AttributeError:
            cache = {}
            setattr(self, CACHE_NAME, cache)
        key = (func, tuple(args), frozenset(kwargs.items()))
        if key not in cache:
            cache[key] = func(self, *args, **kwargs)
        return cache[key]
    return wrapper


def unescape(text):
    """Do reverse escaping."""

    text = text.replace('&', '&')
    text = text.replace('&lt;', '<')
    text = text.replace('&gt;', '>')
    text = text.replace('&quot;', '"')
    text = text.replace('&#39;', '\'')
    return text