filters.py 6.03 KB
Newer Older
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
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
# Copyright 2011-2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

Olga Brani's avatar
Olga Brani committed
34
35
import calendar
import datetime
Olga Brani's avatar
Olga Brani committed
36
import math
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
37

38
39
from collections import defaultdict

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
40
from django import template
41
from django.core.paginator import Paginator, EmptyPage
42
from django.db.models.query import QuerySet
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
43

Olga Brani's avatar
Olga Brani committed
44

45
from astakos.im.settings import PAGINATE_BY, RESOURCES_PRESENTATION_DATA
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
46
from astakos.im.models import RESOURCE_SEPARATOR
Olga Brani's avatar
Olga Brani committed
47

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
48
49
register = template.Library()

50
51
DELIM = ','

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

Olga Brani's avatar
Olga Brani committed
59
60
    month = date.month
    year = date.year
Olga Brani's avatar
Olga Brani committed
61
62
    timestamp = calendar.timegm(date.utctimetuple())

Olga Brani's avatar
Olga Brani committed
63
64
    while date < now:
        months.append((year, month, timestamp))
Olga Brani's avatar
Olga Brani committed
65

Olga Brani's avatar
Olga Brani committed
66
67
68
69
70
71
        if date.month < 12:
            month = date.month + 1
            year = date.year
        else:
            month = 1
            year = date.year + 1
Olga Brani's avatar
Olga Brani committed
72

Olga Brani's avatar
Olga Brani committed
73
        date = datetime.datetime(year=year, month=month, day=1)
Olga Brani's avatar
Olga Brani committed
74
75
        timestamp = calendar.timegm(date.utctimetuple())

Olga Brani's avatar
Olga Brani committed
76
    return months
Olga Brani's avatar
Olga Brani committed
77

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

@register.filter
def to_string(s):
    return str(s)
Olga Brani's avatar
Olga Brani committed
85

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
86
87
@register.filter
def lookup(d, key):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
88
89
90
91
    try:
        return d.get(key)
    except:
        return
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
92

Olga Brani's avatar
Olga Brani committed
93
94
95
96
@register.filter
def lookup_uni(d, key):
    return d.get(unicode(key))

97

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
98
99
@register.filter
def dkeys(d):
Olga Brani's avatar
Olga Brani committed
100
101
    return d.keys()

102

Olga Brani's avatar
Olga Brani committed
103
104
105
@register.filter
def month_name(month_number):
    return calendar.month_name[month_number]
Olga Brani's avatar
Olga Brani committed
106

Olga Brani's avatar
Olga Brani committed
107
108

@register.filter
Olga Brani's avatar
Olga Brani committed
109
def todate(value, arg=''):
Olga Brani's avatar
Olga Brani committed
110
    secs = int(value) / 1000
111
112
113
    return datetime.datetime.fromtimestamp(secs)


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

Olga Brani's avatar
Olga Brani committed
118

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

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

Olga Brani's avatar
Olga Brani committed
151

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

Olga Brani's avatar
Olga Brani committed
158

159
160
161
162
@register.filter
def items(d):
    if isinstance(d, defaultdict):
        return d.iteritems()
Olga Brani's avatar
Olga Brani committed
163
    return d
Olga Brani's avatar
Olga Brani committed
164
165
166
167


@register.filter
def get_value_after_dot(value):
Olga Brani's avatar
Olga Brani committed
168
169
    return value.split(".")[1]

170
171
172
# @register.filter
# def strip_http(value):
#     return value.replace('http://','')[:-1]
Olga Brani's avatar
Olga Brani committed
173
174
175


from math import log
Olga Brani's avatar
Olga Brani committed
176
unit_list = zip(['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], [0, 0, 0, 0, 0, 0])
Olga Brani's avatar
Olga Brani committed
177
178
179
180

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

Olga Brani's avatar
Olga Brani committed
201
202
203
204
205
@register.filter
def isinf(v):
    if math.isinf(v):
        return 'Unlimited'
    else:
Olga Brani's avatar
Fixes    
Olga Brani committed
206
        return v
207

Olga Brani's avatar
Fixes    
Olga Brani committed
208
@register.filter
209
def truncatename(v, max=18, append="..."):
Olga Brani's avatar
Fixes    
Olga Brani committed
210
211
    length = len(v)
    if length>max:
212
        return v[:max] + append
Olga Brani's avatar
Fixes    
Olga Brani committed
213
    else:
214
        return v
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230

@register.filter
def resource_groups(project_definition):
    try:
        grants = project_definition.projectresourcegrant_set
        return grants.values_list('resource__group', flat=True)
    except:
        return ()

@register.filter
def resource_grants(project_definition):
    try:
        grants = project_definition.projectresourcegrant_set
        grants = grants.values_list(
            'resource__name',
            'resource__service__name',
231
            'member_capacity'
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
232
233
234
        )
        return dict((RESOURCE_SEPARATOR.join([e[1], e[0]]), e[2]) for e in grants)
    except:
235
        return {}