outreach-email.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import argparse
  2. import sys
  3. from django.core.management import BaseCommand
  4. from django.template import engines
  5. from django.urls import resolve, reverse
  6. from desecapi.models import User
  7. class Command(BaseCommand):
  8. help = "Reach out to users with an email. Takes email template on stdin."
  9. def add_arguments(self, parser):
  10. parser.add_argument(
  11. "email",
  12. nargs="*",
  13. help="User(s) to contact, identified by their email addresses. "
  14. "Defaults to everyone with outreach_preference = True, excluding inactive users.",
  15. )
  16. parser.add_argument(
  17. "--contentfile",
  18. nargs="?",
  19. type=argparse.FileType("r"),
  20. default=sys.stdin,
  21. help="File to take email content from. Defaults to stdin.",
  22. )
  23. parser.add_argument(
  24. "--reason",
  25. nargs="?",
  26. default="change-outreach-preference",
  27. help="Kind of message to send. Choose from reasons given in serializers.py. Defaults to "
  28. "newsletter with unsubscribe link (reason: change-outreach-preference).",
  29. )
  30. parser.add_argument(
  31. "--subject",
  32. nargs="?",
  33. default=None,
  34. help='Subject, default according to "reason".',
  35. )
  36. def handle(self, *args, **options):
  37. reason = options["reason"]
  38. path = reverse(f"v1:confirm-{reason}", args=["code"])
  39. serializer_class = resolve(path).func.cls.serializer_class
  40. content = options["contentfile"].read().strip()
  41. if not content and options["contentfile"].name != "/dev/null":
  42. raise RuntimeError("Empty content only allowed from /dev/null")
  43. try:
  44. subject = "[deSEC] " + options["subject"]
  45. except TypeError:
  46. subject = None
  47. base_file = f"emails/{reason}/content.txt"
  48. template_code = '{%% extends "%s" %%}' % base_file
  49. if content:
  50. template_code += "{% block content %}" + content + "{% endblock %}"
  51. template = engines["django"].from_string(template_code)
  52. if options["email"]:
  53. users = User.objects.filter(email__in=options["email"])
  54. elif content:
  55. users = User.objects.exclude(is_active=False).filter(
  56. outreach_preference=True
  57. )
  58. else:
  59. raise RuntimeError(
  60. "To send default content, specify recipients explicitly."
  61. )
  62. for user in users:
  63. action = serializer_class.Meta.model(user=user)
  64. serializer_class(action).save(subject=subject, template=template)