Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / templatetags / filters.py @ 5841646f

History | View | Annotate | Download (4.9 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
    print d, key
83
    return d.get(key)
84

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

    
89

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

    
94

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

    
99

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

    
105

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

    
110

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

    
143

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

    
150

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

    
157

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

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

    
166

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

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