root / snf-astakos-app / astakos / im / management / commands / _common.py @ cb14cc6c
History | View | Annotate | Download (6.9 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 |
import uuid |
36 |
|
37 |
from django.core.validators import validate_email |
38 |
from django.utils.timesince import timesince, timeuntil |
39 |
from django.contrib.auth.models import Permission |
40 |
from django.contrib.contenttypes.models import ContentType |
41 |
from django.core.exceptions import FieldError |
42 |
from django.core.management import CommandError |
43 |
|
44 |
from synnefo.lib.ordereddict import OrderedDict |
45 |
from astakos.im.models import AstakosUser |
46 |
|
47 |
DEFAULT_CONTENT_TYPE = None
|
48 |
|
49 |
|
50 |
def get_user(email_or_id, **kwargs): |
51 |
try:
|
52 |
if email_or_id.isdigit():
|
53 |
return AstakosUser.objects.get(id=int(email_or_id)) |
54 |
else:
|
55 |
return AstakosUser.objects.get(email__iexact=email_or_id, **kwargs)
|
56 |
except AstakosUser.DoesNotExist, AstakosUser.MultipleObjectsReturned:
|
57 |
return None |
58 |
|
59 |
|
60 |
def format_bool(b): |
61 |
return 'YES' if b else 'NO' |
62 |
|
63 |
|
64 |
def format_date(d): |
65 |
if not d: |
66 |
return '' |
67 |
|
68 |
if d < datetime.now():
|
69 |
return timesince(d) + ' ago' |
70 |
else:
|
71 |
return 'in ' + timeuntil(d) |
72 |
|
73 |
|
74 |
def format_dict(d, level=1, ident=22): |
75 |
iteritems = d.iteritems() |
76 |
if not isinstance(d, OrderedDict): |
77 |
iteritems = sorted(iteritems)
|
78 |
|
79 |
l = ['%s: %s\n' % (k.rjust(level*ident), format(v, level+1)) |
80 |
for k, v in iteritems] |
81 |
l.insert(0, '\n') |
82 |
return ''.join(l) |
83 |
|
84 |
|
85 |
def format_set(s): |
86 |
return list(s) |
87 |
|
88 |
|
89 |
def format(obj, level=1, ident=22): |
90 |
if isinstance(obj, bool): |
91 |
return format_bool(obj)
|
92 |
elif isinstance(obj, datetime): |
93 |
return format_date(obj)
|
94 |
elif isinstance(obj, dict): |
95 |
return format_dict(obj, level, ident)
|
96 |
elif isinstance(obj, set): |
97 |
return format_set(obj)
|
98 |
else:
|
99 |
return obj
|
100 |
|
101 |
|
102 |
def get_astakosuser_content_type(): |
103 |
try:
|
104 |
return ContentType.objects.get(app_label='im', |
105 |
model='astakosuser')
|
106 |
except:
|
107 |
return DEFAULT_CONTENT_TYPE
|
108 |
|
109 |
|
110 |
def add_user_permission(user, pname): |
111 |
content_type = get_astakosuser_content_type() |
112 |
if user.has_perm(pname):
|
113 |
return 0, None |
114 |
p, created = Permission.objects.get_or_create(codename=pname, |
115 |
name=pname.capitalize(), |
116 |
content_type=content_type) |
117 |
user.user_permissions.add(p) |
118 |
return 1, created |
119 |
|
120 |
|
121 |
def add_group_permission(group, pname): |
122 |
content_type = get_astakosuser_content_type() |
123 |
if pname in [p.codename for p in group.permissions.all()]: |
124 |
return 0, None |
125 |
content_type = ContentType.objects.get(app_label='im',
|
126 |
model='astakosuser')
|
127 |
p, created = Permission.objects.get_or_create(codename=pname, |
128 |
name=pname.capitalize(), |
129 |
content_type=content_type) |
130 |
group.permissions.add(p) |
131 |
return 1, created |
132 |
|
133 |
|
134 |
def remove_user_permission(user, pname): |
135 |
content_type = get_astakosuser_content_type() |
136 |
if user.has_perm(pname):
|
137 |
return 0 |
138 |
try:
|
139 |
p = Permission.objects.get(codename=pname, |
140 |
content_type=content_type) |
141 |
user.user_permissions.remove(p) |
142 |
return 1 |
143 |
except Permission.DoesNotExist:
|
144 |
return -1 |
145 |
|
146 |
|
147 |
def remove_group_permission(group, pname): |
148 |
content_type = get_astakosuser_content_type() |
149 |
if pname not in [p.codename for p in group.permissions.all()]: |
150 |
return 0 |
151 |
try:
|
152 |
p = Permission.objects.get(codename=pname, |
153 |
content_type=content_type) |
154 |
group.permissions.remove(p) |
155 |
return 1 |
156 |
except Permission.DoesNotExist:
|
157 |
return -1 |
158 |
|
159 |
|
160 |
def shortened(s, limit, suffix=True): |
161 |
length = len(s)
|
162 |
if length <= limit:
|
163 |
return s
|
164 |
else:
|
165 |
display = limit - 2
|
166 |
if suffix:
|
167 |
return '..' + s[-display:] |
168 |
else:
|
169 |
return s[:display] + '..' |
170 |
|
171 |
|
172 |
# Copied from snf-cyclades-app/synnefo/management/common.py
|
173 |
# It could be moved to snf-common
|
174 |
def filter_results(objects, filter_by): |
175 |
filter_list = filter_by.split(",")
|
176 |
filter_dict = {} |
177 |
exclude_dict = {} |
178 |
|
179 |
def map_field_type(query): |
180 |
def fix_bool(val): |
181 |
if val.lower() in ("yes", "true", "t"): |
182 |
return True |
183 |
if val.lower() in ("no", "false", "f"): |
184 |
return False |
185 |
return val
|
186 |
|
187 |
if "!=" in query: |
188 |
key, val = query.split("!=")
|
189 |
exclude_dict[key] = fix_bool(val) |
190 |
return
|
191 |
OP_MAP = { |
192 |
">=": "__gte", |
193 |
"=>": "__gte", |
194 |
">": "__gt", |
195 |
"<=": "__lte", |
196 |
"=<": "__lte", |
197 |
"<": "__lt", |
198 |
"=": "", |
199 |
} |
200 |
for op, new_op in OP_MAP.items(): |
201 |
if op in query: |
202 |
key, val = query.split(op) |
203 |
filter_dict[key + new_op] = fix_bool(val) |
204 |
return
|
205 |
|
206 |
map(lambda x: map_field_type(x), filter_list) |
207 |
|
208 |
try:
|
209 |
objects = objects.filter(**filter_dict) |
210 |
return objects.exclude(**exclude_dict)
|
211 |
except FieldError as e: |
212 |
raise CommandError(e)
|
213 |
except Exception as e: |
214 |
raise CommandError("Can not filter results: %s" % e) |
215 |
|
216 |
|
217 |
def is_uuid(s): |
218 |
if s is None: |
219 |
return False |
220 |
try:
|
221 |
uuid.UUID(s) |
222 |
except ValueError: |
223 |
return False |
224 |
else:
|
225 |
return True |
226 |
|
227 |
|
228 |
def is_email(s): |
229 |
if s is None: |
230 |
return False |
231 |
try:
|
232 |
validate_email(s) |
233 |
except:
|
234 |
return False |
235 |
else:
|
236 |
return True |