-
Notifications
You must be signed in to change notification settings - Fork 2k
/
license.py
368 lines (306 loc) · 11.3 KB
/
license.py
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# encoding: utf-8
import datetime
import re
import requests
from ckan.common import config
from ckan.common import asbool
from six import text_type, string_types
from six.moves import map
from ckan.common import _, json
import ckan.lib.maintain as maintain
log = __import__('logging').getLogger(__name__)
class License(object):
"""Domain object for a license."""
def __init__(self, data):
# convert old keys if necessary
if 'is_okd_compliant' in data:
data['od_conformance'] = 'approved' \
if asbool(data['is_okd_compliant']) else ''
del data['is_okd_compliant']
if 'is_osi_compliant' in data:
data['osd_conformance'] = 'approved' \
if asbool(data['is_osi_compliant']) else ''
del data['is_osi_compliant']
self._data = data
for (key, value) in self._data.items():
if key == 'date_created':
# Parse ISO formatted datetime.
value = datetime.datetime(
*list(int(item) for item in re.split('[^\d]', value)))
self._data[key] = value
elif isinstance(value, str):
# Convert str to unicode (keeps Pylons and SQLAlchemy happy).
value = value.decode('utf8')
self._data[key] = value
def __getattr__(self, name):
if name == 'is_okd_compliant':
log.warn('license.is_okd_compliant is deprecated - use '
'od_conformance instead.')
return self._data['od_conformance'] == 'approved'
if name == 'is_osi_compliant':
log.warn('license.is_osi_compliant is deprecated - use '
'osd_conformance instead.')
return self._data['osd_conformance'] == 'approved'
return self._data[name]
@maintain.deprecated("License.__getitem__() is deprecated and will be "
"removed in a future version of CKAN. Instead, "
"please use attribute access.")
def __getitem__(self, key):
'''NB This method is deprecated and will be removed in a future version
of CKAN. Instead, please use attribute access.
'''
return self.__getattr__(key)
def isopen(self):
if not hasattr(self, '_isopen'):
self._isopen = self.od_conformance == 'approved' or \
self.osd_conformance == 'approved'
return self._isopen
@maintain.deprecated("License.as_dict() is deprecated and will be "
"removed in a future version of CKAN. Instead, "
"please use attribute access.")
def as_dict(self):
'''NB This method is deprecated and will be removed in a future version
of CKAN. Instead, please use attribute access.
'''
data = self._data.copy()
if 'date_created' in data:
value = data['date_created']
value = value.isoformat()
data['date_created'] = value
# deprecated keys
if 'od_conformance' in data:
data['is_okd_compliant'] = data['od_conformance'] == 'approved'
if 'osd_conformance' in data:
data['is_osi_compliant'] = data['osd_conformance'] == 'approved'
return data
class LicenseRegister(object):
"""Dictionary-like interface to a group of licenses."""
def __init__(self):
group_url = config.get('licenses_group_url', None)
if group_url:
self.load_licenses(group_url)
else:
default_license_list = [
LicenseNotSpecified(),
LicenseOpenDataCommonsPDDL(),
LicenseOpenDataCommonsOpenDatabase(),
LicenseOpenDataAttribution(),
LicenseCreativeCommonsZero(),
LicenseCreativeCommonsAttribution(),
LicenseCreativeCommonsAttributionShareAlike(),
LicenseGNUFreeDocument(),
LicenseOtherOpen(),
LicenseOtherPublicDomain(),
LicenseOtherAttribution(),
LicenseOpenGovernment(),
LicenseCreativeCommonsNonCommercial(),
LicenseOtherNonCommercial(),
LicenseOtherClosed(),
]
self._create_license_list(default_license_list)
def load_licenses(self, license_url):
try:
if license_url.startswith('file://'):
with open(license_url.replace('file://', ''), 'r') as f:
license_data = json.load(f)
else:
response = requests.get(license_url)
license_data = response.json()
except requests.RequestException as e:
msg = "Couldn't get the licenses file {}: {}".format(license_url, e)
raise Exception(msg)
except ValueError as e:
msg = "Couldn't parse the licenses file {}: {}".format(license_url, e)
raise Exception(msg)
for license in license_data:
if isinstance(license, string_types):
license = license_data[license]
if license.get('title'):
license['title'] = _(license['title'])
self._create_license_list(license_data, license_url)
def _create_license_list(self, license_data, license_url=''):
if isinstance(license_data, dict):
self.licenses = [License(entity) for entity in license_data.values()]
elif isinstance(license_data, list):
self.licenses = [License(entity) for entity in license_data]
else:
msg = "Licenses at %s must be dictionary or list" % license_url
raise ValueError(msg)
def __getitem__(self, key, default=Exception):
for license in self.licenses:
if key == license.id:
return license
if default != Exception:
return default
else:
raise KeyError("License not found: %s" % key)
def get(self, key, default=None):
return self.__getitem__(key, default=default)
def keys(self):
return [license.id for license in self.licenses]
def values(self):
return self.licenses
def items(self):
return [(license.id, license) for license in self.licenses]
def __iter__(self):
return iter(self.keys())
def __len__(self):
return len(self.licenses)
class DefaultLicense(dict):
''' The license was a dict but this did not allow translation of the
title. This is a slightly changed dict that allows us to have the title
as a property and so translated. '''
domain_content = False
domain_data = False
domain_software = False
family = ''
is_generic = False
od_conformance = 'not reviewed'
osd_conformance = 'not reviewed'
maintainer = ''
status = 'active'
url = ''
title = ''
id = ''
keys = ['domain_content',
'id',
'domain_data',
'domain_software',
'family',
'is_generic',
'od_conformance',
'osd_conformance',
'maintainer',
'status',
'url',
'title']
def __getitem__(self, key):
''' behave like a dict but get from attributes '''
if key in self.keys:
value = getattr(self, key)
if isinstance(value, str):
return text_type(value)
else:
return value
else:
raise KeyError()
def copy(self):
''' create a dict of the license used by the licenses api '''
out = {}
for key in self.keys:
out[key] = text_type(getattr(self, key))
return out
class LicenseNotSpecified(DefaultLicense):
id = "notspecified"
is_generic = True
@property
def title(self):
return _("License not specified")
class LicenseOpenDataCommonsPDDL(DefaultLicense):
domain_data = True
id = "odc-pddl"
od_conformance = 'approved'
url = "http://www.opendefinition.org/licenses/odc-pddl"
@property
def title(self):
return _("Open Data Commons Public Domain Dedication and License (PDDL)")
class LicenseOpenDataCommonsOpenDatabase(DefaultLicense):
domain_data = True
id = "odc-odbl"
od_conformance = 'approved'
url = "http://www.opendefinition.org/licenses/odc-odbl"
@property
def title(self):
return _("Open Data Commons Open Database License (ODbL)")
class LicenseOpenDataAttribution(DefaultLicense):
domain_data = True
id = "odc-by"
od_conformance = 'approved'
url = "http://www.opendefinition.org/licenses/odc-by"
@property
def title(self):
return _("Open Data Commons Attribution License")
class LicenseCreativeCommonsZero(DefaultLicense):
domain_content = True
domain_data = True
id = "cc-zero"
od_conformance = 'approved'
url = "http://www.opendefinition.org/licenses/cc-zero"
@property
def title(self):
return _("Creative Commons CCZero")
class LicenseCreativeCommonsAttribution(DefaultLicense):
id = "cc-by"
od_conformance = 'approved'
url = "http://www.opendefinition.org/licenses/cc-by"
@property
def title(self):
return _("Creative Commons Attribution")
class LicenseCreativeCommonsAttributionShareAlike(DefaultLicense):
domain_content = True
id = "cc-by-sa"
od_conformance = 'approved'
url = "http://www.opendefinition.org/licenses/cc-by-sa"
@property
def title(self):
return _("Creative Commons Attribution Share-Alike")
class LicenseGNUFreeDocument(DefaultLicense):
domain_content = True
id = "gfdl"
od_conformance = 'approved'
url = "http://www.opendefinition.org/licenses/gfdl"
@property
def title(self):
return _("GNU Free Documentation License")
class LicenseOtherOpen(DefaultLicense):
domain_content = True
id = "other-open"
is_generic = True
od_conformance = 'approved'
@property
def title(self):
return _("Other (Open)")
class LicenseOtherPublicDomain(DefaultLicense):
domain_content = True
id = "other-pd"
is_generic = True
od_conformance = 'approved'
@property
def title(self):
return _("Other (Public Domain)")
class LicenseOtherAttribution(DefaultLicense):
domain_content = True
id = "other-at"
is_generic = True
od_conformance = 'approved'
@property
def title(self):
return _("Other (Attribution)")
class LicenseOpenGovernment(DefaultLicense):
domain_content = True
id = "uk-ogl"
od_conformance = 'approved'
# CS: bad_spelling ignore
url = "http://reference.data.gov.uk/id/open-government-licence"
@property
def title(self):
# CS: bad_spelling ignore
return _("UK Open Government Licence (OGL)")
class LicenseCreativeCommonsNonCommercial(DefaultLicense):
id = "cc-nc"
url = "http://creativecommons.org/licenses/by-nc/2.0/"
@property
def title(self):
return _("Creative Commons Non-Commercial (Any)")
class LicenseOtherNonCommercial(DefaultLicense):
id = "other-nc"
is_generic = True
@property
def title(self):
return _("Other (Non-Commercial)")
class LicenseOtherClosed(DefaultLicense):
id = "other-closed"
is_generic = True
@property
def title(self):
return _("Other (Not Open)")