Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / templatetags / filters.py @ 6795eb09

History | View | Annotate | Download (6 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, RESOURCES_PRESENTATION_DATA
46
from astakos.im.models import RESOURCE_SEPARATOR
47

    
48
register = template.Library()
49

    
50
DELIM = ','
51

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

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

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

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

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

    
76
    return months
77

    
78
@register.filter
79
def to_unicode(s):
80
    return unicode(s)
81

    
82
@register.filter
83
def to_string(s):
84
    return str(s)
85

    
86
@register.filter
87
def lookup(d, key):
88
    try:
89
        return d.get(key)
90
    except:
91
        return
92

    
93
@register.filter
94
def lookup_uni(d, key):
95
    return d.get(unicode(key))
96

    
97

    
98
@register.filter
99
def dkeys(d):
100
    return d.keys()
101

    
102

    
103
@register.filter
104
def month_name(month_number):
105
    return calendar.month_name[month_number]
106

    
107

    
108
@register.filter
109
def todate(value, arg=''):
110
    secs = int(value) / 1000
111
    return datetime.datetime.fromtimestamp(secs)
112

    
113

    
114
# @register.filter
115
# def rcut(value, chars='/'):
116
#     return value.rstrip(chars)
117

    
118

    
119
@register.filter
120
def paginate(l, args):
121
    l = l or []
122
    page, delim, sorting = args.partition(DELIM)
123
    if sorting:
124
        if isinstance(l, QuerySet):
125
            l = l.order_by(sorting)
126
        elif isinstance(l, list):
127
            default = ''
128
            if sorting.endswith('_date'):
129
                default = datetime.datetime.utcfromtimestamp(0)
130
            l.sort(key=lambda i: getattr(i, sorting)
131
                   if getattr(i, sorting) else default)
132
    paginator = Paginator(l, PAGINATE_BY)
133
    try:
134
        paginator.len
135
    except AttributeError:
136
        paginator._count = len(list(l))
137

    
138
    try:
139
        page_number = int(page)
140
    except ValueError:
141
        if page == 'last':
142
            page_number = paginator.num_pages
143
        else:
144
            page_number = 1
145
    try:
146
        page = paginator.page(page_number)
147
    except EmptyPage:
148
        page = paginator.page(1)
149
    return page
150

    
151

    
152
@register.filter
153
def concat(str1, str2):
154
    if not str2:
155
        return str(str1)
156
    return '%s%s%s' % (str1, DELIM, str2)
157

    
158

    
159
@register.filter
160
def items(d):
161
    if isinstance(d, defaultdict):
162
        return d.iteritems()
163
    return d
164

    
165

    
166
@register.filter
167
def get_value_after_dot(value):
168
    return value.split(".")[1]
169

    
170
# @register.filter
171
# def strip_http(value):
172
#     return value.replace('http://','')[:-1]
173

    
174

    
175
from math import log
176
unit_list = zip(['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], [0, 0, 0, 0, 0, 0])
177

    
178
@register.filter
179
def sizeof_fmt(num):
180
    """Human friendly file size"""
181
    try:
182
        num = float(num)
183
    except:
184
        return
185
    else:
186
        if math.isinf(num):
187
            return 'Unlimited'
188
        if num > 1:
189
            exponent = min(int(log(num, 1024)), len(unit_list) - 1)
190
            quotient = float(num) / 1024**exponent
191
            unit, num_decimals = unit_list[exponent]
192
            format_string = '{0:.%sf} {1}' % (num_decimals)
193
            return format_string.format(quotient, unit)
194
        if num == 0:
195
            return '0 bytes'
196
        if num == 1:
197
            return '1 byte'
198
        else:
199
           return '0'
200

    
201
@register.filter
202
def isinf(v):
203
    if math.isinf(v):
204
        return 'Unlimited'
205
    else:
206
        return v
207

    
208
@register.filter
209
def truncatename(v, max=18, append="..."):
210
    length = len(v)
211
    if length>max:
212
        return v[:max] + append
213
    else:
214
        return v
215

    
216
@register.filter
217
def resource_groups(project_definition):
218
    try:
219
        grants = project_definition.projectresourcegrant_set
220
        return grants.values_list('resource__group', flat=True)
221
    except:
222
        return ()
223

    
224
@register.filter
225
def resource_grants(project_definition):
226
    try:
227
        grants = project_definition.projectresourcegrant_set
228
        grants = grants.values_list(
229
            'resource__name',
230
            'resource__service__name',
231
            'member_capacity'
232
        )
233
        return dict((RESOURCE_SEPARATOR.join([e[1], e[0]]), e[2]) for e in grants)
234
    except:
235
        return {}