Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / templatetags / filters.py @ 8998f09a

History | View | Annotate | Download (5.4 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
from synnefo.lib.ordereddict import OrderedDict
45

    
46
from astakos.im import settings
47
from astakos.im.models import ProjectResourceGrant
48

    
49
register = template.Library()
50

    
51
DELIM = ','
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
@register.filter
80
def to_unicode(s):
81
    return unicode(s)
82

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

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

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

    
98

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

    
103

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

    
108

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

    
114

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

    
119

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

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

    
152

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

    
159

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

    
166

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

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

    
175

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

    
179
@register.filter
180
def sizeof_fmt(num):
181
    """Human friendly file size"""
182
    return ProjectResourceGrant.display_filesize(num)
183

    
184
@register.filter
185
def truncatename(v, max=18, append="..."):
186
    length = len(v)
187
    if length>max:
188
        return v[:max] + append
189
    else:
190
        return v
191

    
192
@register.filter
193
def resource_groups(project_definition):
194
    try:
195
        grants = project_definition.projectresourcegrant_set
196
        return grants.values_list('resource__group', flat=True)
197
    except:
198
        return ()
199

    
200
@register.filter
201
def resource_grants(project_definition):
202
    try:
203
        grants = project_definition.projectresourcegrant_set
204
        grants = grants.values_list(
205
            'resource__name',
206
            'member_capacity'
207
        )
208
        return dict((e[0], e[1]) for e in grants)
209
    except:
210
        return {}