utils.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. from datetime import timedelta
  2. import bleach
  3. from markdown import Markdown
  4. from unidecode import unidecode
  5. from django.core.urlresolvers import reverse
  6. from django.template.defaultfilters import slugify as django_slugify
  7. from django.utils.translation import ugettext_lazy as _, ungettext_lazy
  8. def slugify(string):
  9. string = unicode(string)
  10. string = unidecode(string)
  11. return django_slugify(string.replace('_', ' '))
  12. """
  13. Utils for resolving requests destination
  14. """
  15. def _is_request_path_under_misago(request):
  16. # We are assuming that forum_index link is root of all Misago links
  17. forum_index = reverse('misago:index')
  18. path_info = request.path_info
  19. if len(forum_index) > len(path_info):
  20. return False
  21. return path_info[:len(forum_index)] == forum_index
  22. def is_request_to_misago(request):
  23. try:
  24. return request._request_to_misago
  25. except AttributeError:
  26. request._request_to_misago = _is_request_path_under_misago(request)
  27. return request._request_to_misago
  28. """
  29. Utility that humanizes time amount.
  30. Expects number of seconds as first argument
  31. """
  32. def time_amount(value):
  33. delta = timedelta(seconds=value)
  34. units_dict = {
  35. 'd': delta.days,
  36. 'h': 0,
  37. 'm': 0,
  38. 's': delta.seconds,
  39. }
  40. if units_dict['s'] >= 3600:
  41. units_dict['h'] = units_dict['s'] / 3600
  42. units_dict['s'] -= units_dict['h'] * 3600
  43. if units_dict['s'] >= 60:
  44. units_dict['m'] = units_dict['s'] / 60
  45. units_dict['s'] -= units_dict['m'] * 60
  46. precisions = []
  47. if units_dict['d']:
  48. string = ungettext_lazy(
  49. '%(days)s day', '%(days)s days', units_dict['d'])
  50. precisions.append(string % {'days': units_dict['d']})
  51. if units_dict['h']:
  52. string = ungettext_lazy(
  53. '%(hours)s hour', '%(hours)s hours', units_dict['h'])
  54. precisions.append(string % {'hours': units_dict['h']})
  55. if units_dict['m']:
  56. string = ungettext_lazy(
  57. '%(minutes)s minute', '%(minutes)s minutes', units_dict['m'])
  58. precisions.append(string % {'minutes': units_dict['m']})
  59. if units_dict['s']:
  60. string = ungettext_lazy(
  61. '%(seconds)s second', '%(seconds)s seconds', units_dict['s'])
  62. precisions.append(string % {'seconds': units_dict['s']})
  63. if not precisions:
  64. precisions.append(_("0 seconds"))
  65. if len(precisions) == 1:
  66. return precisions[0]
  67. else:
  68. formats = {
  69. 'first_part': ', '.join(precisions[:-1]),
  70. 'and_part': precisions[-1],
  71. }
  72. return _("%(first_part)s and %(and_part)s") % formats
  73. """
  74. MD subset for use for enchancing items descriptions
  75. """
  76. MD_SUBSET_FORBID_SYNTAX = (
  77. # References are evil
  78. 'reference', 'reference', 'image_reference', 'short_reference',
  79. # Blocks are evil too
  80. 'hashheader', 'setextheader', 'code', 'quote', 'hr', 'olist', 'ulist',
  81. )
  82. def subset_markdown(text):
  83. if not text:
  84. return ''
  85. md = Markdown(safe_mode='escape', extensions=['nl2br'])
  86. for key in md.preprocessors.keys():
  87. if key in MD_SUBSET_FORBID_SYNTAX:
  88. del md.preprocessors[key]
  89. for key in md.inlinePatterns.keys():
  90. if key in MD_SUBSET_FORBID_SYNTAX:
  91. del md.inlinePatterns[key]
  92. for key in md.parser.blockprocessors.keys():
  93. if key in MD_SUBSET_FORBID_SYNTAX:
  94. del md.parser.blockprocessors[key]
  95. for key in md.treeprocessors.keys():
  96. if key in MD_SUBSET_FORBID_SYNTAX:
  97. del md.treeprocessors[key]
  98. for key in md.postprocessors.keys():
  99. if key in MD_SUBSET_FORBID_SYNTAX:
  100. del md.postprocessors[key]
  101. return bleach.linkify(md.convert(text))