Statistics
| Branch: | Tag: | Revision:

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

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
def format_dict(d, level=1, ident=22):
70
    iteritems = d.iteritems()
71
    if not isinstance(d, OrderedDict):
72
        iteritems = sorted(iteritems)
73

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

    
79
def format_set(s):
80
    return list(s)
81

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

    
94
def get_astakosuser_content_type():
95
    try:
96
        return ContentType.objects.get(app_label='im',
97
                                       model='astakosuser')
98
    except:
99
        return DEFAULT_CONTENT_TYPE
100

    
101

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

    
112

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

    
125

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

    
138

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

    
151
def shortened(s, limit, suffix=True):
152
    length = len(s)
153
    if length <= limit:
154
        return s
155
    else:
156
        display = limit - 2
157
        if suffix:
158
            return '..' + s[-display:]
159
        else:
160
            return s[:display] + '..'