utils.py 5.1 KB

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