-
Notifications
You must be signed in to change notification settings - Fork 2k
/
helpers.py
1444 lines (1170 loc) · 47.4 KB
/
helpers.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=UTF-8
"""Helper functions
Consists of functions to typically be used within templates, but also
available to Controllers. This module is available to templates as 'h'.
"""
import email.utils
import datetime
import logging
import re
import urllib
import pprint
import copy
from urllib import urlencode
import urlparse
from paste.deploy.converters import asbool
from webhelpers.html import escape, HTML, literal, url_escape
from webhelpers.html.tools import mail_to
from webhelpers.html.tags import *
from webhelpers.markdown import markdown
from webhelpers import paginate
from webhelpers.text import truncate
import webhelpers.date as date
from pylons import url as _pylons_default_url
from pylons.decorators.cache import beaker_cache
from pylons import config
from routes import redirect_to as _redirect_to
from routes import url_for as _routes_default_url_for
from alphabet_paginate import AlphaPage
import i18n
import ckan.exceptions
from pylons import request
from pylons import session
from pylons import c, g
from pylons.i18n import _, ungettext
import ckan.lib.fanstatic_resources as fanstatic_resources
import ckan.model as model
import ckan.lib.formatters as formatters
import ckan.plugins as p
import ckan.plugins.toolkit as toolkit
get_available_locales = i18n.get_available_locales
get_locales_dict = i18n.get_locales_dict
log = logging.getLogger(__name__)
try:
from collections import OrderedDict # from python 2.7
except ImportError:
from sqlalchemy.util import OrderedDict
try:
import json
except ImportError:
import simplejson as json
_log = logging.getLogger(__name__)
def redirect_to(*args, **kw):
'''A routes.redirect_to wrapper to retain the i18n settings'''
kw['__ckan_no_root'] = True
if are_there_flash_messages():
kw['__no_cache__'] = True
return _redirect_to(url_for(*args, **kw))
def url(*args, **kw):
"""Create url adding i18n information if selected
wrapper for pylons.url"""
locale = kw.pop('locale', None)
my_url = _pylons_default_url(*args, **kw)
return _add_i18n_to_url(my_url, locale=locale, **kw)
def url_for(*args, **kw):
"""Create url adding i18n information if selected
wrapper for routes.url_for"""
locale = kw.pop('locale', None)
# remove __ckan_no_root and add after to not pollute url
no_root = kw.pop('__ckan_no_root', False)
# routes will get the wrong url for APIs if the ver is not provided
if kw.get('controller') == 'api':
ver = kw.get('ver')
if not ver:
raise Exception('api calls must specify the version! e.g. ver=1')
# fix ver to include the slash
kw['ver'] = '/%s' % ver
my_url = _routes_default_url_for(*args, **kw)
kw['__ckan_no_root'] = no_root
return _add_i18n_to_url(my_url, locale=locale, **kw)
def url_for_static(*args, **kw):
"""Create url for static content that does not get translated
eg css, js
wrapper for routes.url_for"""
# make sure that if we specify the url that it is not unicode
if args:
args = (str(args[0]),) + args[1:]
my_url = _routes_default_url_for(*args, **kw)
return my_url
def _add_i18n_to_url(url_to_amend, **kw):
# If the locale keyword param is provided then the url is rewritten
# using that locale .If return_to is provided this is used as the url
# (as part of the language changing feature).
# A locale of default will not add locale info to the url.
default_locale = False
locale = kw.pop('locale', None)
no_root = kw.pop('__ckan_no_root', False)
allowed_locales = ['default'] + i18n.get_locales()
if locale and locale not in allowed_locales:
locale = None
if locale:
if locale == 'default':
default_locale = True
else:
try:
locale = request.environ.get('CKAN_LANG')
default_locale = request.environ.get('CKAN_LANG_IS_DEFAULT', True)
except TypeError:
default_locale = True
try:
root = request.environ.get('SCRIPT_NAME', '')
except TypeError:
root = ''
if kw.get('qualified', False):
# if qualified is given we want the full url ie http://...
root = _routes_default_url_for('/', qualified=True)[:-1] + root
# ckan.root_path is defined when we have none standard language
# position in the url
root_path = config.get('ckan.root_path', None)
if root_path:
# FIXME this can be written better once the merge
# into the ecportal core is done - Toby
# we have a special root specified so use that
if default_locale:
root = re.sub('/{{LANG}}', '', root_path)
else:
root = re.sub('{{LANG}}', locale, root_path)
# make sure we don't have a trailing / on the root
if root[-1] == '/':
root = root[:-1]
url = url_to_amend[len(re.sub('/{{LANG}}', '', root_path)):]
url = '%s%s' % (root, url)
root = re.sub('/{{LANG}}', '', root_path)
else:
if default_locale:
url = url_to_amend
else:
# we need to strip the root from the url and the add it before
# the language specification.
url = url_to_amend[len(root):]
url = '%s/%s%s' % (root, locale, url)
# stop the root being added twice in redirects
if no_root:
url = url_to_amend[len(root):]
if not default_locale:
url = '/%s%s' % (locale, url)
if url == '/packages':
error = 'There is a broken url being created %s' % kw
raise ckan.exceptions.CkanUrlException(error)
return url
def full_current_url():
''' Returns the fully qualified current url (eg http://...) useful
for sharing etc '''
return(url_for(request.environ['CKAN_CURRENT_URL'], qualified=True))
def lang():
''' Return the language code for the current locale eg `en` '''
return request.environ.get('CKAN_LANG')
def lang_native_name(lang=None):
''' Return the langage name currently used in it's localised form
either from parameter or current environ setting'''
lang = lang or lang()
locale = get_locales_dict().get(lang)
if locale:
return locale.display_name or locale.english_name
return lang
class Message(object):
"""A message returned by ``Flash.pop_messages()``.
Converting the message to a string returns the message text. Instances
also have the following attributes:
* ``message``: the message text.
* ``category``: the category specified when the message was created.
"""
def __init__(self, category, message, allow_html):
self.category = category
self.message = message
self.allow_html = allow_html
def __str__(self):
return self.message
__unicode__ = __str__
def __html__(self):
if self.allow_html:
return self.message
else:
return escape(self.message)
class _Flash(object):
# List of allowed categories. If None, allow any category.
categories = ["", "alert-info", "alert-error", "alert-success"]
# Default category if none is specified.
default_category = ""
def __init__(self, session_key="flash", categories=None,
default_category=None):
self.session_key = session_key
if categories is not None:
self.categories = categories
if default_category is not None:
self.default_category = default_category
if self.categories and self.default_category not in self.categories:
raise ValueError("unrecognized default category %r"
% (self.default_category,))
def __call__(self, message, category=None, ignore_duplicate=False,
allow_html=False):
if not category:
category = self.default_category
elif self.categories and category not in self.categories:
raise ValueError("unrecognized category %r" % (category,))
# Don't store Message objects in the session, to avoid unpickling
# errors in edge cases.
new_message_tuple = (category, message, allow_html)
messages = session.setdefault(self.session_key, [])
# ``messages`` is a mutable list, so changes to the local variable are
# reflected in the session.
if ignore_duplicate:
for i, m in enumerate(messages):
if m[1] == message:
if m[0] != category:
messages[i] = new_message_tuple
session.save()
return # Original message found, so exit early.
messages.append(new_message_tuple)
session.save()
def pop_messages(self):
messages = session.pop(self.session_key, [])
# only save session if it has changed
if messages:
session.save()
return [Message(*m) for m in messages]
def are_there_messages(self):
return bool(session.get(self.session_key))
flash = _Flash()
# this is here for backwards compatability
_flash = flash
def flash_notice(message, allow_html=False):
''' Show a flash message of type notice '''
flash(message, category='alert-info', allow_html=allow_html)
def flash_error(message, allow_html=False):
''' Show a flash message of type error '''
flash(message, category='alert-error', allow_html=allow_html)
def flash_success(message, allow_html=False):
''' Show a flash message of type success '''
flash(message, category='alert-success', allow_html=allow_html)
def are_there_flash_messages():
''' Returns True if there are flash messages for the current user '''
return flash.are_there_messages()
def nav_link(text, controller, **kwargs):
'''
params
class_: pass extra class(s) to add to the <a> tag
icon: name of ckan icon to use within the link
condition: if False then no link is returned
'''
kwargs['controller'] = controller
if kwargs.get('inner_span'):
text = literal('<span>') + text + literal('</span>')
icon = kwargs.pop('icon', None)
if icon:
text = literal('<i class="icon-large icon-%s"></i> ' % icon) + text
class_ = _link_class(kwargs)
if kwargs.pop('condition', True):
link = link_to(
text,
url_for(**kwargs),
class_=class_
)
else:
link = ''
return link
def _link_class(kwargs):
''' creates classes for the link_to calls '''
highlight_actions = kwargs.pop('highlight_actions',
kwargs.get('action', '')).split(' ')
if (c.controller == kwargs.get('controller')
and c.action in highlight_actions):
active = ' active'
else:
active = ''
return kwargs.pop('class_', '') + active
def nav_named_link(text, name, **kwargs):
class_ = _link_class(kwargs)
return link_to(
text,
url_for(name, **kwargs),
class_=class_
)
def subnav_link(text, action, **kwargs):
kwargs['action'] = action
class_ = _link_class(kwargs)
return link_to(
text,
url_for(**kwargs),
class_=class_
)
def subnav_named_route(text, routename, **kwargs):
""" Generate a subnav element based on a named route """
# FIXME this is the same as _nav_named_link
# they should be combined
class_ = _link_class(kwargs)
return link_to(
text,
url_for(str(routename), **kwargs),
class_=class_
)
def build_nav_main(*args):
''' build a set of menu items.
args: tuples of (menu type, title) eg ('login', _('Login'))
outputs <li><a href="...">title</a></li>
'''
output = ''
for item in args:
menu_item, title = item[:2]
if len(item) == 3 and not check_access(item[2]):
continue
output += _make_menu_item(menu_item, title)
return output
def _make_menu_item(menu_item, title):
if menu_item not in _menu_items:
log.error('menu item `%s` cannot be found' % menu_item)
return literal('<li><a href="#">') + title + literal('</a></li>')
item = _menu_items[menu_item]
if 'name' in item:
link = nav_named_link(title, **item)
elif 'url' in item:
return literal('<li><a href="%s">' % item.url) + title + literal('</a></li>')
else:
item = copy.copy(_menu_items[menu_item])
controller = item.pop('controller')
link = nav_link(title, controller, **item)
return literal('<li>') + link + literal('</li>')
def default_group_type():
return str(config.get('ckan.default.group_type', 'group'))
_menu_items = {
'add dataset': dict(controller='package', action='new'),
'search': dict(controller='package',
action='search',
highlight_actions='index search'),
'default_group': dict(name='%s_index' % default_group_type(),
controller='group',
highlight_actions='index search'),
'about': dict(controller='home', action='about'),
'login': dict(controller='user', action='login'),
'register': dict(controller='user', action='register'),
}
def get_facet_items_dict(facet, limit=10, exclude_active=False):
'''Return the list of unselected facet items for the given facet, sorted
by count.
Returns the list of unselected facet contraints or facet items (e.g. tag
names like "russian" or "tolstoy") for the given search facet (e.g.
"tags"), sorted by facet item count (i.e. the number of search results that
match each facet item).
Reads the complete list of facet items for the given facet from
c.search_facets, and filters out the facet items that the user has already
selected.
Arguments:
facet -- the name of the facet to filter.
limit -- the max. number of facet items to return.
exclude_active -- only return unselected facets.
'''
if not c.search_facets or \
not c.search_facets.get(facet) or \
not c.search_facets.get(facet).get('items'):
return []
facets = []
for facet_item in c.search_facets.get(facet)['items']:
if not len(facet_item['name'].strip()):
continue
if not (facet, facet_item['name']) in request.params.items():
facets.append(dict(active=False, **facet_item))
elif not exclude_active:
facets.append(dict(active=True, **facet_item))
facets = sorted(facets, key=lambda item: item['count'], reverse=True)
if c.search_facets_limits:
limit = c.search_facets_limits.get(facet)
if limit:
return facets[:limit]
else:
return facets
def unselected_facet_items(facet, limit=10):
'''Return the list of unselected facet items for the given facet, sorted
by count.
Returns the list of unselected facet contraints or facet items (e.g. tag
names like "russian" or "tolstoy") for the given search facet (e.g.
"tags"), sorted by facet item count (i.e. the number of search results that
match each facet item).
Reads the complete list of facet items for the given facet from
c.search_facets, and filters out the facet items that the user has already
selected.
Arguments:
facet -- the name of the facet to filter.
limit -- the max. number of facet items to return.
'''
return get_facet_items_dict(facet, limit=limit, exclude_active=True)
def get_facet_title(name):
# if this is set in the config use this
config_title = config.get('search.facets.%s.title' % name)
if config_title:
return config_title
facet_titles = {'groups': _('Groups'),
'tags': _('Tags'),
'res_format': _('Formats'),
'license': _('Licence'), }
return facet_titles.get(name, name.capitalize())
def get_param_int(name, default=10):
return int(request.params.get(name, default))
def _url_with_params(url, params):
if not params:
return url
params = [(k, v.encode('utf-8') if isinstance(v, basestring) else str(v)) \
for k, v in params]
return url + u'?' + urlencode(params)
def _search_url(params):
url = url_for(controller='package', action='search')
return _url_with_params(url, params)
def sorted_extras(list_):
''' Used for outputting package extras '''
output = []
for extra in sorted(list_, key=lambda x: x['key']):
if extra.get('state') == 'deleted':
continue
k, v = extra['key'], extra['value']
if k in g.package_hide_extras:
continue
if isinstance(v, (list, tuple)):
v = ", ".join(map(unicode, v))
output.append((k, v))
return output
def check_access(action, data_dict=None):
from ckan.logic import check_access as check_access_logic, NotAuthorized
context = {'model': model,
'user': c.user or c.author}
try:
check_access_logic(action, context, data_dict)
authorized = True
except NotAuthorized:
authorized = False
return authorized
def linked_user(user, maxlength=0, avatar=20):
if user in [model.PSEUDO_USER__LOGGED_IN, model.PSEUDO_USER__VISITOR]:
return user
if not isinstance(user, model.User):
user_name = unicode(user)
user = model.User.get(user_name)
if not user:
return user_name
if user:
name = user.name if model.User.VALID_NAME.match(user.name) else user.id
icon = gravatar(email_hash=user.email_hash, size=avatar)
displayname = user.display_name
if maxlength and len(user.display_name) > maxlength:
displayname = displayname[:maxlength] + '...'
return icon + u' ' + link_to(displayname,
url_for(controller='user', action='read', id=name))
def group_name_to_title(name):
group = model.Group.by_name(name)
if group is not None:
return group.display_name
return name
def markdown_extract(text, extract_length=190):
if (text is None) or (text.strip() == ''):
return ''
plain = re.sub(r'<.*?>', '', markdown(text))
return literal(unicode(truncate(plain, length=extract_length, indicator='...', whole_word=True)))
def icon_url(name):
return url_for_static('/images/icons/%s.png' % name)
def icon_html(url, alt=None, inline=True):
classes = ''
if inline:
classes += 'inline-icon '
return literal(('<img src="%s" height="16px" width="16px" alt="%s" ' +
'class="%s" /> ') % (url, alt, classes))
def icon(name, alt=None, inline=True):
return icon_html(icon_url(name), alt, inline)
def resource_icon(res):
if False:
icon_name = 'page_white'
# if (res.is_404?): icon_name = 'page_white_error'
# also: 'page_white_gear'
# also: 'page_white_link'
return icon(icon_name)
else:
return icon(format_icon(res.get('format', '')))
def format_icon(_format):
_format = _format.lower()
if ('json' in _format): return 'page_white_cup'
if ('csv' in _format): return 'page_white_gear'
if ('xls' in _format): return 'page_white_excel'
if ('zip' in _format): return 'page_white_compressed'
if ('api' in _format): return 'page_white_database'
if ('plain text' in _format): return 'page_white_text'
if ('xml' in _format): return 'page_white_code'
return 'page_white'
def dict_list_reduce(list_, key, unique=True):
''' Take a list of dicts and create a new one containing just the
values for the key with unique values if requested. '''
new_list = []
for item in list_:
value = item.get(key)
if not value or (unique and value in new_list):
continue
new_list.append(value)
return new_list
def linked_gravatar(email_hash, size=100, default=None):
return literal(
'<a href="https://gravatar.com/" target="_blank" ' +
'title="%s">' % _('Update your avatar at gravatar.com') +
'%s</a>' % gravatar(email_hash, size, default)
)
_VALID_GRAVATAR_DEFAULTS = ['404', 'mm', 'identicon', 'monsterid',
'wavatar', 'retro']
def gravatar(email_hash, size=100, default=None):
if default is None:
default = config.get('ckan.gravatar_default', 'identicon')
if not default in _VALID_GRAVATAR_DEFAULTS:
# treat the default as a url
default = urllib.quote(default, safe='')
return literal('''<img src="http://gravatar.com/avatar/%s?s=%d&d=%s"
class="gravatar" width="%s" height="%s" />'''
% (email_hash, size, default, size, size)
)
def pager_url(page, partial=None, **kwargs):
routes_dict = _pylons_default_url.environ['pylons.routes_dict']
kwargs['controller'] = routes_dict['controller']
kwargs['action'] = routes_dict['action']
if routes_dict.get('id'):
kwargs['id'] = routes_dict['id']
kwargs['page'] = page
return url(**kwargs)
class Page(paginate.Page):
# Curry the pager method of the webhelpers.paginate.Page class, so we have
# our custom layout set as default.
def pager(self, *args, **kwargs):
kwargs.update(
format=u"<div class='pagination pagination-centered'><ul>$link_previous ~2~ $link_next</ul></div>",
symbol_previous=u'«', symbol_next=u'»',
curpage_attr={'class': 'active'}, link_attr={}
)
return super(Page, self).pager(*args, **kwargs)
# Put each page link into a <li> (for Bootstrap to style it)
def _pagerlink(self, page, text, extra_attributes=None):
anchor = super(Page, self)._pagerlink(page, text)
extra_attributes = extra_attributes or {}
return HTML.li(anchor, **extra_attributes)
# Change 'current page' link from <span> to <li><a>
# and '..' into '<li><a>..'
# (for Bootstrap to style them properly)
def _range(self, regexp_match):
html = super(Page, self)._range(regexp_match)
# Convert ..
dotdot = '<span class="pager_dotdot">..</span>'
dotdot_link = HTML.li(HTML.a('...', href='#'), class_='disabled')
html = re.sub(dotdot, dotdot_link, html)
# Convert current page
text = '%s' % self.page
current_page_span = str(HTML.span(c=text, **self.curpage_attr))
current_page_link = self._pagerlink(self.page, text,
extra_attributes=self.curpage_attr)
return re.sub(current_page_span, current_page_link, html)
def render_datetime(datetime_, date_format=None, with_hours=False):
'''Render a datetime object or timestamp string as a pretty string
(Y-m-d H:m).
If timestamp is badly formatted, then a blank string is returned.
'''
if not date_format:
date_format = '%b %d, %Y'
if with_hours:
date_format += ', %H:%M'
if isinstance(datetime_, datetime.datetime):
return datetime_.strftime(date_format)
elif isinstance(datetime_, basestring):
try:
datetime_ = date_str_to_datetime(datetime_)
except TypeError:
return ''
except ValueError:
return ''
return datetime_.strftime(date_format)
else:
return ''
def date_str_to_datetime(date_str):
'''Convert ISO-like formatted datestring to datetime object.
This function converts ISO format date- and datetime-strings into
datetime objects. Times may be specified down to the microsecond. UTC
offset or timezone information may **not** be included in the string.
Note - Although originally documented as parsing ISO date(-times), this
function doesn't fully adhere to the format. This function will
throw a ValueError if the string contains UTC offset information.
So in that sense, it is less liberal than ISO format. On the
other hand, it is more liberal of the accepted delimiters between
the values in the string. Also, it allows microsecond precision,
despite that not being part of the ISO format.
'''
time_tuple = re.split('[^\d]+', date_str, maxsplit=5)
# Extract seconds and microseconds
if len(time_tuple) >= 6:
m = re.match('(?P<seconds>\d{2})(\.(?P<microseconds>\d{6}))?$',
time_tuple[5])
if not m:
raise ValueError('Unable to parse %s as seconds.microseconds' %
time_tuple[5])
seconds = int(m.groupdict().get('seconds'))
microseconds = int(m.groupdict(0).get('microseconds'))
time_tuple = time_tuple[:5] + [seconds, microseconds]
return datetime.datetime(*map(int, time_tuple))
def parse_rfc_2822_date(date_str, assume_utc=True):
"""
Parse a date string of the form specified in RFC 2822, and return a
datetime.
RFC 2822 is the date format used in HTTP headers. It should contain
timezone information, but that cannot be relied upon.
If date_str doesn't contain timezone information, then the 'assume_utc'
flag determines whether we assume this string is local (with respect to the
server running this code), or UTC. In practice, what this means is that if
assume_utc is True, then the returned datetime is 'aware', with an
associated tzinfo of offset zero. Otherwise, the returned datetime is
'naive'.
If timezone information is available in date_str, then the returned
datetime is 'aware', ie - it has an associated tz_info object.
Returns None if the string cannot be parsed as a valid datetime.
"""
time_tuple = email.utils.parsedate_tz(date_str)
# Not parsable
if not time_tuple:
return None
# No timezone information available in the string
if time_tuple[-1] is None and not assume_utc:
return datetime.datetime.fromtimestamp(
email.utils.mktime_tz(time_tuple))
else:
offset = 0 if time_tuple[-1] is None else time_tuple[-1]
tz_info = _RFC2282TzInfo(offset)
return datetime.datetime(*time_tuple[:6], microsecond=0, tzinfo=tz_info)
class _RFC2282TzInfo(datetime.tzinfo):
"""
A datetime.tzinfo implementation used by parse_rfc_2822_date() function.
In order to return timezone information, a concrete implementation of
datetime.tzinfo is required. This class represents tzinfo that knows
about it's offset from UTC, has no knowledge of daylight savings time, and
no knowledge of the timezone name.
"""
def __init__(self, offset):
"""
offset from UTC in seconds.
"""
self.offset = datetime.timedelta(seconds=offset)
def utcoffset(self, dt):
return self.offset
def dst(self, dt):
"""
Dates parsed from an RFC 2822 string conflate timezone and dst, and so
it's not possible to determine whether we're in DST or not, hence
returning None.
"""
return None
def tzname(self, dt):
return None
def time_ago_in_words_from_str(date_str, granularity='month'):
if date_str:
return date.time_ago_in_words(date_str_to_datetime(date_str),
granularity=granularity)
else:
return _('Unknown')
def button_attr(enable, type='primary'):
if enable:
return 'class="btn %s"' % type
return 'disabled class="btn disabled"'
def dataset_display_name(package_or_package_dict):
if isinstance(package_or_package_dict, dict):
return package_or_package_dict.get('title', '') or \
package_or_package_dict.get('name', '')
else:
return package_or_package_dict.title or package_or_package_dict.name
def dataset_link(package_or_package_dict):
if isinstance(package_or_package_dict, dict):
name = package_or_package_dict['name']
else:
name = package_or_package_dict.name
text = dataset_display_name(package_or_package_dict)
return link_to(
text,
url_for(controller='package', action='read', id=name)
)
# TODO: (?) support resource objects as well
def resource_display_name(resource_dict):
name = resource_dict.get('name', None)
description = resource_dict.get('description', None)
url = resource_dict.get('url')
if name:
return name
elif description:
description = description.split('.')[0]
max_len = 60
if len(description) > max_len:
description = description[:max_len] + '...'
return description
elif url:
return url
else:
noname_string = _('no name')
return '[%s] %s' % (noname_string, resource_dict['id'])
def resource_link(resource_dict, package_id):
text = resource_display_name(resource_dict)
url = url_for(controller='package',
action='resource_read',
id=package_id,
resource_id=resource_dict['id'])
return link_to(text, url)
def related_item_link(related_item_dict):
text = related_item_dict.get('title', '')
url = url_for(controller='related',
action='read',
id=related_item_dict['id'])
return link_to(text, url)
def tag_link(tag):
url = url_for(controller='tag', action='read', id=tag['name'])
return link_to(tag['name'], url)
def group_link(group):
url = url_for(controller='group', action='read', id=group['name'])
return link_to(group['title'], url)
def dump_json(obj, **kw):
return json.dumps(obj, **kw)
def _get_template_name():
#FIX ME THIS IS BROKEN
''' helper function to get the currently/last rendered template name '''
return c.__debug_info[-1]['template_name']
def auto_log_message():
if (c.action == 'new'):
return _('Created new dataset.')
elif (c.action == 'editresources'):
return _('Edited resources.')
elif (c.action == 'edit'):
return _('Edited settings.')
return ''
def activity_div(template, activity, actor, object=None, target=None):
actor = '<span class="actor">%s</span>' % actor
if object:
object = '<span class="object">%s</span>' % object
if target:
target = '<span class="target">%s</span>' % target
rendered_datetime = render_datetime(activity['timestamp'])
date = '<span class="date">%s</span>' % rendered_datetime
template = template.format(actor=actor, date=date,
object=object, target=target)
template = '<div class="activity">%s %s</div>' % (template, date)
return literal(template)
def snippet(template_name, **kw):
''' This function is used to load html snippets into pages. keywords
can be used to pass parameters into the snippet rendering '''
import ckan.lib.base as base
return base.render_snippet(template_name, **kw)
def convert_to_dict(object_type, objs):
''' This is a helper function for converting lists of objects into
lists of dicts. It is for backwards compatability only. '''
def dictize_revision_list(revision, context):
# conversionof revision lists
def process_names(items):
array = []
for item in items:
array.append(item.name)
return array
rev = {'id': revision.id,
'state': revision.state,
'timestamp': revision.timestamp,
'author': revision.author,
'packages': process_names(revision.packages),
'groups': process_names(revision.groups),
'message': revision.message, }
return rev
import lib.dictization.model_dictize as md
converters = {'package': md.package_dictize,
'revisions': dictize_revision_list}
converter = converters[object_type]
items = []
context = {'model': model}
for obj in objs:
item = converter(obj, context)
items.append(item)
return items
# these are the types of objects that can be followed
_follow_objects = ['dataset', 'user', 'group']
def follow_button(obj_type, obj_id):
'''Return a follow button for the given object type and id.
If the user is not logged in return an empty string instead.
:param obj_type: the type of the object to be followed when the follow
button is clicked, e.g. 'user' or 'dataset'
:type obj_type: string
:param obj_id: the id of the object to be followed when the follow button
is clicked
:type obj_id: string
:returns: a follow button as an HTML snippet
:rtype: string
'''
import ckan.logic as logic
obj_type = obj_type.lower()
assert obj_type in _follow_objects
# If the user is logged in show the follow/unfollow button
if c.user:
context = {'model': model, 'session': model.Session, 'user': c.user}
action = 'am_following_%s' % obj_type
following = logic.get_action(action)(context, {'id': obj_id})
return snippet('snippets/follow_button.html',
following=following,
obj_id=obj_id,
obj_type=obj_type)
return ''