utils.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from hashlib import md5
  2. from django.conf import settings
  3. from django.core.cache import cache
  4. from django.utils.encoding import force_bytes
  5. from ..markup import common_flavour
  6. from .models import Agreement, UserAgreement
  7. def set_agreement_as_active(agreement, commit=False):
  8. agreement.is_active = True
  9. queryset = Agreement.objects.filter(type=agreement.type).exclude(pk=agreement.pk)
  10. queryset.update(is_active=False)
  11. if commit:
  12. agreement.save(update_fields=["is_active"])
  13. Agreement.objects.invalidate_cache()
  14. def get_required_user_agreement(user, agreements):
  15. if user.is_anonymous:
  16. return None
  17. for agreement_type, _ in Agreement.TYPE_CHOICES:
  18. agreement = agreements.get(agreement_type)
  19. if agreement and agreement["id"] not in user.agreements:
  20. try:
  21. return Agreement.objects.get(id=agreement["id"])
  22. except Agreement.DoesNotExist:
  23. # possible stale cache
  24. Agreement.invalidate_cache()
  25. def get_parsed_agreement_text(request, agreement):
  26. if not agreement.text:
  27. return None
  28. cache_name = "misago_legal_%s_%s" % (agreement.pk, agreement.last_modified_on or "")
  29. cached_content = cache.get(cache_name)
  30. unparsed_content = agreement.text
  31. checksum_source = force_bytes("%s:%s" % (unparsed_content, settings.SECRET_KEY))
  32. unparsed_checksum = md5(checksum_source).hexdigest()
  33. if cached_content and cached_content.get("checksum") == unparsed_checksum:
  34. return cached_content["parsed"]
  35. parsed = common_flavour(request, None, unparsed_content)["parsed_text"]
  36. cached_content = {"checksum": unparsed_checksum, "parsed": parsed}
  37. cache.set(cache_name, cached_content)
  38. return cached_content["parsed"]
  39. def save_user_agreement_acceptance(user, agreement, commit=False):
  40. user.agreements.append(agreement.id)
  41. UserAgreement.objects.create(agreement=agreement, user=user)
  42. if commit:
  43. user.save(update_fields=["agreements"])