utils.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import os
  4. import hashlib
  5. import binascii
  6. import base64
  7. import html2text
  8. import re
  9. import sys
  10. from datetime import date, timedelta
  11. from contextlib import contextmanager
  12. from functools import wraps
  13. from django.utils import translation
  14. from django.core.mail import EmailMultiAlternatives
  15. from django.core.files.storage import FileSystemStorage
  16. from django.conf import settings
  17. from django.template.loader import get_template
  18. from django.template import Context, TemplateDoesNotExist
  19. from django.contrib.sites.models import Site
  20. # Stockage des fichiers privés (comme les factures par exemple)
  21. private_files_storage = FileSystemStorage(location=settings.PRIVATE_FILES_ROOT)
  22. # regexp which matches for ex irc://irc.example.tld/#channel
  23. re_chat_url = re.compile(r'(?P<protocol>\w+://)(?P<server>[\w\.]+)/(?P<channel>.*)')
  24. def str_or_none(obj):
  25. return str(obj) if obj else None
  26. def rstrip_str(s, suffix):
  27. """Return a copy of the string [s] with the string [suffix] removed from
  28. the end (if [s] ends with [suffix], otherwise return s)."""
  29. if s.endswith(suffix):
  30. return s[:-len(suffix)]
  31. else:
  32. return s
  33. def ldap_hash(password):
  34. """Hash a password for use with LDAP. If the password is already hashed,
  35. do nothing.
  36. Implementation details: Django provides us with a unicode object, so
  37. we have to encode/decode it as needed to switch between unicode and
  38. bytes. The code should work fine with both python2 and python3.
  39. """
  40. if password and not password.startswith('{SSHA}'):
  41. salt = binascii.hexlify(os.urandom(8))
  42. digest = hashlib.sha1(password.encode("utf-8") + salt).digest()
  43. return '{SSHA}' + base64.b64encode(digest + salt).decode("utf-8")
  44. else:
  45. return password
  46. def send_templated_email(to, subject_template, body_template, context={}, attachements=[], **kwargs):
  47. """
  48. Send a multialternative email based on html and optional txt template.
  49. :param **kwargs: extra-args pased as-is to EmailMultiAlternatives()
  50. """
  51. # Ensure arrays when needed
  52. if not isinstance(to, list):
  53. to = [to]
  54. if not isinstance(attachements, list):
  55. attachements = [attachements]
  56. # Add domain in context
  57. context['domain'] = Site.objects.get_current()
  58. # If .html/.txt is specified in template name remove it
  59. body_template = body_template.split('.')[0]
  60. subject_template = subject_template.split('.')[0]
  61. # Get html template for body, fail if not exists
  62. template_html = get_template('%s.html' % (body_template,))
  63. html_content = template_html.render(Context(context))
  64. # Get txt template for subject, fail if not exists
  65. subject_template = get_template('%s.txt' % (subject_template,))
  66. subject = subject_template.render(Context(context))
  67. # Get rid of newlines
  68. subject = subject.strip().replace('\n', '')
  69. # Try to get a txt version, convert from html to markdown style
  70. # (using html2text) if fail
  71. try:
  72. template_txt = get_template('%s.txt' % (body_template,))
  73. text_content = template_txt.render_to_string(Context(context))
  74. except TemplateDoesNotExist:
  75. text_content = html2text.html2text(html_content)
  76. # make multipart email default : text, alternative : html
  77. msg = EmailMultiAlternatives(subject=subject, body=text_content, to=to, **kwargs)
  78. msg.attach_alternative(html_content, "text/html")
  79. # Set attachements
  80. for attachement in attachements:
  81. msg.attach_file(attachement)
  82. # Send email
  83. msg.send()
  84. def delete_selected(modeladmin, request, queryset):
  85. """Overrides QuerySet's delete() function to remove objects one by one
  86. so, that they are deleted in the LDAP (Redmine issue #195)."""
  87. for obj in queryset:
  88. obj.delete()
  89. delete_selected.short_description = "Supprimer tous les objets sélectionnés."
  90. # Time-related functions
  91. def in_one_year():
  92. return date.today() + timedelta(365)
  93. def start_of_month():
  94. return date(date.today().year, date.today().month, 1)
  95. def end_of_month():
  96. today = date.today()
  97. if today.month == 12:
  98. return date(today.year + 1, 1, 1) - timedelta(days=1)
  99. else:
  100. return date(today.year, today.month + 1, 1) - timedelta(days=1)
  101. @contextmanager
  102. def respect_language(language):
  103. """Context manager that changes the current translation language for
  104. all code inside the following block.
  105. Can be used like this::
  106. from amorce.utils import respect_language
  107. def my_func(language='fr'):
  108. with respect_language(language):
  109. pass
  110. """
  111. if language:
  112. prev = translation.get_language()
  113. translation.activate(language)
  114. try:
  115. yield
  116. finally:
  117. translation.activate(prev)
  118. else:
  119. yield
  120. def respects_language(fun):
  121. """Associated decorator"""
  122. @wraps(fun)
  123. def _inner(*args, **kwargs):
  124. with respect_language(kwargs.pop('language', None)):
  125. return fun(*args, **kwargs)
  126. return _inner
  127. def disable_for_loaddata(signal_handler):
  128. """Decorator for post_save events that disables them when loading
  129. data from fixtures."""
  130. @wraps(signal_handler)
  131. def wrapper(*args, **kwargs):
  132. if kwargs['raw']:
  133. return
  134. signal_handler(*args, **kwargs)
  135. return wrapper
  136. def postgresql_regexp(regexp):
  137. """ Make a PCRE regexp PostgreSQL compatible (kinda)
  138. PostgreSQL forbids using capture-group names, this function removes them.
  139. :param regexp: a PCRE regexp or pattern
  140. :return a PostgreSQL regexp
  141. """
  142. try:
  143. original_pattern = regexp.pattern
  144. except AttributeError:
  145. original_pattern = regexp
  146. return re.sub(
  147. r'\?P<.*?>', '', original_pattern)
  148. if __name__ == '__main__':
  149. # ldap_hash expects an unicode string
  150. print(ldap_hash(sys.argv[1].decode("utf-8")))