Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / templatetags / filters.py @ 6ed0e4a6

History | View | Annotate | Download (5.1 kB)

1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
import calendar
35
import datetime
36
import math
37

    
38
from collections import defaultdict
39

    
40
from django import template
41
from django.core.paginator import Paginator, EmptyPage
42
from django.db.models.query import QuerySet
43

    
44

    
45
from astakos.im.settings import PAGINATE_BY
46

    
47

    
48
register = template.Library()
49

    
50
DELIM = ','
51

    
52

    
53
@register.filter
54
def monthssince(joined_date):
55
    now = datetime.datetime.now()
56
    date = datetime.datetime(
57
        year=joined_date.year, month=joined_date.month, day=1)
58
    months = []
59

    
60
    month = date.month
61
    year = date.year
62
    timestamp = calendar.timegm(date.utctimetuple())
63

    
64
    while date < now:
65
        months.append((year, month, timestamp))
66

    
67
        if date.month < 12:
68
            month = date.month + 1
69
            year = date.year
70
        else:
71
            month = 1
72
            year = date.year + 1
73

    
74
        date = datetime.datetime(year=year, month=month, day=1)
75
        timestamp = calendar.timegm(date.utctimetuple())
76

    
77
    return months
78

    
79

    
80
@register.filter
81
def lookup(d, key):
82
    return d.get(key)
83

    
84
@register.filter
85
def lookup_uni(d, key):
86
    return d.get(unicode(key))
87

    
88

    
89
@register.filter
90
def dkeys(d):
91
    return d.keys()
92

    
93

    
94
@register.filter
95
def month_name(month_number):
96
    return calendar.month_name[month_number]
97

    
98

    
99
@register.filter
100
def todate(value, arg=''):
101
    secs = int(value) / 1000
102
    return datetime.datetime.fromtimestamp(secs)
103

    
104

    
105
@register.filter
106
def rcut(value, chars='/'):
107
    return value.rstrip(chars)
108

    
109

    
110
@register.filter
111
def paginate(l, args):
112
    l = l or []
113
    page, delim, sorting = args.partition(DELIM)
114
    if sorting:
115
        if isinstance(l, QuerySet):
116
            l = l.order_by(sorting)
117
        elif isinstance(l, list):
118
            default = ''
119
            if sorting.endswith('_date'):
120
                default = datetime.datetime.utcfromtimestamp(0)
121
            l.sort(key=lambda i: getattr(i, sorting)
122
                   if getattr(i, sorting) else default)
123
    paginator = Paginator(l, PAGINATE_BY)
124
    try:
125
        paginator.len
126
    except AttributeError:
127
        paginator._count = len(list(l))
128
    
129
    try:
130
        page_number = int(page)
131
    except ValueError:
132
        if page == 'last':
133
            page_number = paginator.num_pages
134
        else:
135
            page_number = 1
136
    try:
137
        page = paginator.page(page_number)
138
    except EmptyPage:
139
        page = paginator.page(1)
140
    return page
141

    
142

    
143
@register.filter
144
def concat(str1, str2):
145
    if not str2:
146
        return str(str1)
147
    return '%s%s%s' % (str1, DELIM, str2)
148

    
149

    
150
@register.filter
151
def items(d):
152
    if isinstance(d, defaultdict):
153
        return d.iteritems()
154
    return d
155

    
156

    
157
@register.filter
158
def get_value_after_dot(value):
159
    return value.split(".")[1]
160

    
161
@register.filter
162
def strip_http(value):
163
    return value.replace('http://','')[:-1]
164

    
165

    
166
from math import log
167
unit_list = zip(['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], [0, 0, 0, 0, 0, 0])
168

    
169
@register.filter
170
def sizeof_fmt(num):
171
    
172
    """Human friendly file size"""
173
    if math.isinf(num):
174
        return 'Unlimited'
175
    if num > 1:
176
        exponent = min(int(log(num, 1024)), len(unit_list) - 1)
177
        quotient = float(num) / 1024**exponent
178
        unit, num_decimals = unit_list[exponent]
179
        format_string = '{0:.%sf} {1}' % (num_decimals)
180
        return format_string.format(quotient, unit)
181
    if num == 0:
182
        return '0 bytes'
183
    if num == 1:
184
        return '1 byte'
185
    else:
186
       return '';
187
   
188
@register.filter
189
def isinf(v):
190
    if math.isinf(v):
191
        return 'Unlimited'
192
    else:
193
        return v
194
    
195
@register.filter
196
def truncatename(v):
197
    max = 18
198
    length = len(v)
199
    if length>max:
200
        return v[:max]+'...'
201
    else:
202
        return v[:20]