Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / _common.py @ 865849d7

History | View | Annotate | Download (5.2 kB)

1
# Copyright 2012, 2013 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
from datetime import datetime
35

    
36
from django.utils.timesince import timesince, timeuntil
37
from django.contrib.auth.models import Permission
38
from django.contrib.contenttypes.models import ContentType
39

    
40
from synnefo.lib.ordereddict import OrderedDict
41
from astakos.im.models import AstakosUser
42

    
43
DEFAULT_CONTENT_TYPE = None
44

    
45

    
46
def get_user(email_or_id, **kwargs):
47
    try:
48
        if email_or_id.isdigit():
49
            return AstakosUser.objects.get(id=int(email_or_id))
50
        else:
51
            return AstakosUser.objects.get(email__iexact=email_or_id, **kwargs)
52
    except AstakosUser.DoesNotExist, AstakosUser.MultipleObjectsReturned:
53
        return None
54

    
55

    
56
def format_bool(b):
57
    return 'YES' if b else 'NO'
58

    
59

    
60
def format_date(d):
61
    if not d:
62
        return ''
63

    
64
    if d < datetime.now():
65
        return timesince(d) + ' ago'
66
    else:
67
        return 'in ' + timeuntil(d)
68

    
69

    
70
def format_dict(d, level=1, ident=22):
71
    iteritems = d.iteritems()
72
    if not isinstance(d, OrderedDict):
73
        iteritems = sorted(iteritems)
74

    
75
    l = ['%s: %s\n' % (k.rjust(level*ident), format(v, level+1))
76
         for k, v in iteritems]
77
    l.insert(0, '\n')
78
    return ''.join(l)
79

    
80

    
81
def format_set(s):
82
    return list(s)
83

    
84

    
85
def format(obj, level=1, ident=22):
86
    if isinstance(obj, bool):
87
        return format_bool(obj)
88
    elif isinstance(obj, datetime):
89
        return format_date(obj)
90
    elif isinstance(obj, dict):
91
        return format_dict(obj, level, ident)
92
    elif isinstance(obj, set):
93
        return format_set(obj)
94
    else:
95
        return obj
96

    
97

    
98
def get_astakosuser_content_type():
99
    try:
100
        return ContentType.objects.get(app_label='im',
101
                                       model='astakosuser')
102
    except:
103
        return DEFAULT_CONTENT_TYPE
104

    
105

    
106
def add_user_permission(user, pname):
107
    content_type = get_astakosuser_content_type()
108
    if user.has_perm(pname):
109
        return 0, None
110
    p, created = Permission.objects.get_or_create(codename=pname,
111
                                                  name=pname.capitalize(),
112
                                                  content_type=content_type)
113
    user.user_permissions.add(p)
114
    return 1, created
115

    
116

    
117
def add_group_permission(group, pname):
118
    content_type = get_astakosuser_content_type()
119
    if pname in [p.codename for p in group.permissions.all()]:
120
        return 0, None
121
    content_type = ContentType.objects.get(app_label='im',
122
                                           model='astakosuser')
123
    p, created = Permission.objects.get_or_create(codename=pname,
124
                                                  name=pname.capitalize(),
125
                                                  content_type=content_type)
126
    group.permissions.add(p)
127
    return 1, created
128

    
129

    
130
def remove_user_permission(user, pname):
131
    content_type = get_astakosuser_content_type()
132
    if user.has_perm(pname):
133
        return 0
134
    try:
135
        p = Permission.objects.get(codename=pname,
136
                                   content_type=content_type)
137
        user.user_permissions.remove(p)
138
        return 1
139
    except Permission.DoesNotExist:
140
        return -1
141

    
142

    
143
def remove_group_permission(group, pname):
144
    content_type = get_astakosuser_content_type()
145
    if pname not in [p.codename for p in group.permissions.all()]:
146
        return 0
147
    try:
148
        p = Permission.objects.get(codename=pname,
149
                                   content_type=content_type)
150
        group.permissions.remove(p)
151
        return 1
152
    except Permission.DoesNotExist:
153
        return -1
154

    
155

    
156
def shortened(s, limit, suffix=True):
157
    length = len(s)
158
    if length <= limit:
159
        return s
160
    else:
161
        display = limit - 2
162
        if suffix:
163
            return '..' + s[-display:]
164
        else:
165
            return s[:display] + '..'