utils.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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 ldap_hash(password):
  27. """Hash a password for use with LDAP. If the password is already hashed,
  28. do nothing.
  29. Implementation details: Django provides us with a unicode object, so
  30. we have to encode/decode it as needed to switch between unicode and
  31. bytes. The code should work fine with both python2 and python3.
  32. """
  33. if password and not password.startswith('{SSHA}'):
  34. salt = binascii.hexlify(os.urandom(8))
  35. digest = hashlib.sha1(password.encode("utf-8") + salt).digest()
  36. return '{SSHA}' + base64.b64encode(digest + salt).decode("utf-8")
  37. else:
  38. return password
  39. def send_templated_email(to, subject_template, body_template, context={}, attachements=[], **kwargs):
  40. """
  41. Send a multialternative email based on html and optional txt template.
  42. :param **kwargs: extra-args pased as-is to EmailMultiAlternatives()
  43. """
  44. # Ensure arrays when needed
  45. if not isinstance(to, list):
  46. to = [to]
  47. if not isinstance(attachements, list):
  48. attachements = [attachements]
  49. # Add domain in context
  50. context['domain'] = Site.objects.get_current()
  51. # If .html/.txt is specified in template name remove it
  52. body_template = body_template.split('.')[0]
  53. subject_template = subject_template.split('.')[0]
  54. # Get html template for body, fail if not exists
  55. template_html = get_template('%s.html' % (body_template,))
  56. html_content = template_html.render(Context(context))
  57. # Get txt template for subject, fail if not exists
  58. subject_template = get_template('%s.txt' % (subject_template,))
  59. subject = subject_template.render(Context(context))
  60. # Get rid of newlines
  61. subject = subject.strip().replace('\n', '')
  62. # Try to get a txt version, convert from html to markdown style
  63. # (using html2text) if fail
  64. try:
  65. template_txt = get_template('%s.txt' % (body_template,))
  66. text_content = template_txt.render_to_string(Context(context))
  67. except TemplateDoesNotExist:
  68. text_content = html2text.html2text(html_content)
  69. # make multipart email default : text, alternative : html
  70. msg = EmailMultiAlternatives(subject=subject, body=text_content, to=to, **kwargs)
  71. msg.attach_alternative(html_content, "text/html")
  72. # Set attachements
  73. for attachement in attachements:
  74. msg.attach_file(attachement)
  75. # Send email
  76. msg.send()
  77. def delete_selected(modeladmin, request, queryset):
  78. """Overrides QuerySet's delete() function to remove objects one by one
  79. so, that they are deleted in the LDAP (Redmine issue #195)."""
  80. for obj in queryset:
  81. obj.delete()
  82. delete_selected.short_description = "Supprimer tous les objets sélectionnés."
  83. # Time-related functions
  84. def in_one_year():
  85. return date.today() + timedelta(365)
  86. def start_of_month():
  87. return date(date.today().year, date.today().month, 1)
  88. def end_of_month():
  89. today = date.today()
  90. if today.month == 12:
  91. return date(today.year + 1, 1, 1) - timedelta(days=1)
  92. else:
  93. return date(today.year, today.month + 1, 1) - timedelta(days=1)
  94. @contextmanager
  95. def respect_language(language):
  96. """Context manager that changes the current translation language for
  97. all code inside the following block.
  98. Can be used like this::
  99. from amorce.utils import respect_language
  100. def my_func(language='fr'):
  101. with respect_language(language):
  102. pass
  103. """
  104. if language:
  105. prev = translation.get_language()
  106. translation.activate(language)
  107. try:
  108. yield
  109. finally:
  110. translation.activate(prev)
  111. else:
  112. yield
  113. def respects_language(fun):
  114. """Associated decorator"""
  115. @wraps(fun)
  116. def _inner(*args, **kwargs):
  117. with respect_language(kwargs.pop('language', None)):
  118. return fun(*args, **kwargs)
  119. return _inner
  120. def disable_for_loaddata(signal_handler):
  121. """Decorator for post_save events that disables them when loading
  122. data from fixtures."""
  123. @wraps(signal_handler)
  124. def wrapper(*args, **kwargs):
  125. if kwargs['raw']:
  126. return
  127. signal_handler(*args, **kwargs)
  128. return wrapper
  129. if __name__ == '__main__':
  130. # ldap_hash expects an unicode string
  131. print(ldap_hash(sys.argv[1].decode("utf-8")))