We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Notification and newsletter emails should only go to active users
At the moment these emails are sent to all users, deactivated or not.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `app/grandchallenge/notifications/tasks.py`
Content:
```
1 from celery import shared_task
2 from django.core.paginator import Paginator
3 from django.utils.timezone import now
4 
5 from grandchallenge.notifications.emails import send_unread_notifications_email
6 from grandchallenge.profiles.models import UserProfile
7 
8 
9 @shared_task
10 def send_unread_notification_emails():
11     profiles = (
12         UserProfile.objects.filter(
13             receive_notification_emails=True, user__notification__read=False
14         )
15         .distinct()
16         .prefetch_related("user__notification_set")
17         .order_by("pk")
18     )
19     paginator = Paginator(profiles, 1000)
20 
21     for page_nr in paginator.page_range:
22         current_page_profiles = paginator.page(page_nr).object_list
23         current_time = now()
24         recipients = {}
25         for profile in current_page_profiles:
26             unread_notifications = [
27                 n
28                 for n in profile.user.notification_set.all()
29                 if not n.read
30                 and (
31                     profile.notification_email_last_sent_at is None
32                     or n.created > profile.notification_email_last_sent_at
33                 )
34             ]
35             if unread_notifications:
36                 recipients[profile] = len(unread_notifications)
37                 profile.notification_email_last_sent_at = current_time
38 
39         UserProfile.objects.bulk_update(
40             current_page_profiles, ["notification_email_last_sent_at"]
41         )
42         send_unread_notifications_email(recipients)
43
```

Path: `app/grandchallenge/emails/tasks.py`
Content:
```
1 from celery import shared_task
2 from django.conf import settings
3 from django.contrib.auth import get_user_model
4 from django.contrib.sites.models import Site
5 from django.core.exceptions import ObjectDoesNotExist
6 from django.core.mail import EmailMultiAlternatives, get_connection
7 from django.core.paginator import Paginator
8 from django.template.loader import render_to_string
9 from django.utils.html import strip_tags
10 from django.utils.timezone import now
11 
12 from grandchallenge.core.templatetags.bleach import md2html
13 from grandchallenge.emails.models import Email
14 from grandchallenge.emails.utils import SendActionChoices
15 from grandchallenge.subdomains.utils import reverse
16 
17 
18 def get_receivers(action):
19     if action == SendActionChoices.MAILING_LIST:
20         receivers = (
21             get_user_model()
22             .objects.filter(user_profile__receive_newsletter=True)
23             .order_by("pk")
24         )
25     elif action == SendActionChoices.STAFF:
26         receivers = (
27             get_user_model().objects.filter(is_staff=True).order_by("pk")
28         )
29     elif action == SendActionChoices.CHALLENGE_ADMINS:
30         receivers = (
31             get_user_model()
32             .objects.filter(
33                 groups__admins_of_challenge__isnull=False,
34                 user_profile__receive_newsletter=True,
35             )
36             .distinct()
37             .order_by("pk")
38         )
39     elif action == SendActionChoices.READER_STUDY_EDITORS:
40         receivers = (
41             get_user_model()
42             .objects.filter(
43                 groups__editors_of_readerstudy__isnull=False,
44                 user_profile__receive_newsletter=True,
45             )
46             .distinct()
47             .order_by("pk")
48         )
49     elif action == SendActionChoices.ALGORITHM_EDITORS:
50         receivers = (
51             get_user_model()
52             .objects.filter(
53                 groups__editors_of_algorithm__isnull=False,
54                 user_profile__receive_newsletter=True,
55             )
56             .distinct()
57             .order_by("pk")
58         )
59 
60     return receivers
61 
62 
63 def send_mass_html_email(datatuple):
64     connection = get_connection()
65     messages = []
66     for subject, message, sender, recipient, html in datatuple:
67         email = EmailMultiAlternatives(
68             subject, message, sender, recipient, connection=connection
69         )
70         email.attach_alternative(html, "text/html")
71         messages.append(email)
72     return connection.send_messages(messages)
73 
74 
75 @shared_task(**settings.CELERY_TASK_DECORATOR_KWARGS["acks-late-micro-short"])
76 def send_bulk_email(action, email_pk):
77     try:
78         email = Email.objects.filter(sent=False).get(pk=email_pk)
79     except ObjectDoesNotExist:
80         return
81     subject = email.subject
82     body = email.body
83     html_body = md2html(body)
84     receivers = get_receivers(action=action)
85     paginator = Paginator(receivers, 100)
86     site = Site.objects.get_current()
87     if email.status_report:
88         start_page = email.status_report["last_processed_batch"]
89     else:
90         start_page = 0
91     for page_nr in paginator.page_range[start_page:]:
92         messages = []
93         for recipient in paginator.page(page_nr).object_list:
94             user = get_user_model().objects.get(pk=recipient.pk)
95             link = reverse(
96                 "profile-update", kwargs={"username": user.username}
97             )
98             html_content = render_to_string(
99                 "vendor/mailgun_transactional_emails/action.html",
100                 {
101                     "title": subject,
102                     "username": user.username,
103                     "content": html_body,
104                     "link": link,
105                 },
106             )
107             html_content_without_linebreaks = html_content.replace("\n", "")
108             text_content = strip_tags(html_content_without_linebreaks)
109             messages.append(
110                 (
111                     f"[{site.domain.lower()}] {subject}",
112                     text_content,
113                     settings.DEFAULT_FROM_EMAIL,
114                     [user.email],
115                     html_content_without_linebreaks,
116                 )
117             )
118         send_mass_html_email(messages)
119         email.status_report = {"last_processed_batch": page_nr}
120         email.save()
121 
122     email.sent = True
123     email.sent_at = now()
124     email.status_report = None
125     email.save()
126
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/app/grandchallenge/emails/tasks.py b/app/grandchallenge/emails/tasks.py
--- a/app/grandchallenge/emails/tasks.py
+++ b/app/grandchallenge/emails/tasks.py
@@ -19,12 +19,16 @@
     if action == SendActionChoices.MAILING_LIST:
         receivers = (
             get_user_model()
-            .objects.filter(user_profile__receive_newsletter=True)
+            .objects.filter(
+                user_profile__receive_newsletter=True, is_active=True
+            )
             .order_by("pk")
         )
     elif action == SendActionChoices.STAFF:
         receivers = (
-            get_user_model().objects.filter(is_staff=True).order_by("pk")
+            get_user_model()
+            .objects.filter(is_staff=True, is_active=True)
+            .order_by("pk")
         )
     elif action == SendActionChoices.CHALLENGE_ADMINS:
         receivers = (
@@ -32,6 +36,7 @@
             .objects.filter(
                 groups__admins_of_challenge__isnull=False,
                 user_profile__receive_newsletter=True,
+                is_active=True,
             )
             .distinct()
             .order_by("pk")
@@ -42,6 +47,7 @@
             .objects.filter(
                 groups__editors_of_readerstudy__isnull=False,
                 user_profile__receive_newsletter=True,
+                is_active=True,
             )
             .distinct()
             .order_by("pk")
@@ -52,6 +58,7 @@
             .objects.filter(
                 groups__editors_of_algorithm__isnull=False,
                 user_profile__receive_newsletter=True,
+                is_active=True,
             )
             .distinct()
             .order_by("pk")
diff --git a/app/grandchallenge/notifications/tasks.py b/app/grandchallenge/notifications/tasks.py
--- a/app/grandchallenge/notifications/tasks.py
+++ b/app/grandchallenge/notifications/tasks.py
@@ -10,7 +10,9 @@
 def send_unread_notification_emails():
     profiles = (
         UserProfile.objects.filter(
-            receive_notification_emails=True, user__notification__read=False
+            receive_notification_emails=True,
+            user__notification__read=False,
+            user__is_active=True,
         )
         .distinct()
         .prefetch_related("user__notification_set")

{"golden_diff": "diff --git a/app/grandchallenge/emails/tasks.py b/app/grandchallenge/emails/tasks.py\n--- a/app/grandchallenge/emails/tasks.py\n+++ b/app/grandchallenge/emails/tasks.py\n@@ -19,12 +19,16 @@\n     if action == SendActionChoices.MAILING_LIST:\r\n         receivers = (\r\n             get_user_model()\r\n-            .objects.filter(user_profile__receive_newsletter=True)\r\n+            .objects.filter(\r\n+                user_profile__receive_newsletter=True, is_active=True\r\n+            )\r\n             .order_by(\"pk\")\r\n         )\r\n     elif action == SendActionChoices.STAFF:\r\n         receivers = (\r\n-            get_user_model().objects.filter(is_staff=True).order_by(\"pk\")\r\n+            get_user_model()\r\n+            .objects.filter(is_staff=True, is_active=True)\r\n+            .order_by(\"pk\")\r\n         )\r\n     elif action == SendActionChoices.CHALLENGE_ADMINS:\r\n         receivers = (\r\n@@ -32,6 +36,7 @@\n             .objects.filter(\r\n                 groups__admins_of_challenge__isnull=False,\r\n                 user_profile__receive_newsletter=True,\r\n+                is_active=True,\r\n             )\r\n             .distinct()\r\n             .order_by(\"pk\")\r\n@@ -42,6 +47,7 @@\n             .objects.filter(\r\n                 groups__editors_of_readerstudy__isnull=False,\r\n                 user_profile__receive_newsletter=True,\r\n+                is_active=True,\r\n             )\r\n             .distinct()\r\n             .order_by(\"pk\")\r\n@@ -52,6 +58,7 @@\n             .objects.filter(\r\n                 groups__editors_of_algorithm__isnull=False,\r\n                 user_profile__receive_newsletter=True,\r\n+                is_active=True,\r\n             )\r\n             .distinct()\r\n             .order_by(\"pk\")\r\ndiff --git a/app/grandchallenge/notifications/tasks.py b/app/grandchallenge/notifications/tasks.py\n--- a/app/grandchallenge/notifications/tasks.py\n+++ b/app/grandchallenge/notifications/tasks.py\n@@ -10,7 +10,9 @@\n def send_unread_notification_emails():\r\n     profiles = (\r\n         UserProfile.objects.filter(\r\n-            receive_notification_emails=True, user__notification__read=False\r\n+            receive_notification_emails=True,\r\n+            user__notification__read=False,\r\n+            user__is_active=True,\r\n         )\r\n         .distinct()\r\n         .prefetch_related(\"user__notification_set\")\n", "issue": "Notification and newsletter emails should only go to active users\nAt the moment these emails are sent to all users, deactivated or not.\n", "before_files": [{"content": "from celery import shared_task\r\nfrom django.core.paginator import Paginator\r\nfrom django.utils.timezone import now\r\n\r\nfrom grandchallenge.notifications.emails import send_unread_notifications_email\r\nfrom grandchallenge.profiles.models import UserProfile\r\n\r\n\r\n@shared_task\r\ndef send_unread_notification_emails():\r\n    profiles = (\r\n        UserProfile.objects.filter(\r\n            receive_notification_emails=True, user__notification__read=False\r\n        )\r\n        .distinct()\r\n        .prefetch_related(\"user__notification_set\")\r\n        .order_by(\"pk\")\r\n    )\r\n    paginator = Paginator(profiles, 1000)\r\n\r\n    for page_nr in paginator.page_range:\r\n        current_page_profiles = paginator.page(page_nr).object_list\r\n        current_time = now()\r\n        recipients = {}\r\n        for profile in current_page_profiles:\r\n            unread_notifications = [\r\n                n\r\n                for n in profile.user.notification_set.all()\r\n                if not n.read\r\n                and (\r\n                    profile.notification_email_last_sent_at is None\r\n                    or n.created > profile.notification_email_last_sent_at\r\n                )\r\n            ]\r\n            if unread_notifications:\r\n                recipients[profile] = len(unread_notifications)\r\n                profile.notification_email_last_sent_at = current_time\r\n\r\n        UserProfile.objects.bulk_update(\r\n            current_page_profiles, [\"notification_email_last_sent_at\"]\r\n        )\r\n        send_unread_notifications_email(recipients)\r\n", "path": "app/grandchallenge/notifications/tasks.py"}, {"content": "from celery import shared_task\r\nfrom django.conf import settings\r\nfrom django.contrib.auth import get_user_model\r\nfrom django.contrib.sites.models import Site\r\nfrom django.core.exceptions import ObjectDoesNotExist\r\nfrom django.core.mail import EmailMultiAlternatives, get_connection\r\nfrom django.core.paginator import Paginator\r\nfrom django.template.loader import render_to_string\r\nfrom django.utils.html import strip_tags\r\nfrom django.utils.timezone import now\r\n\r\nfrom grandchallenge.core.templatetags.bleach import md2html\r\nfrom grandchallenge.emails.models import Email\r\nfrom grandchallenge.emails.utils import SendActionChoices\r\nfrom grandchallenge.subdomains.utils import reverse\r\n\r\n\r\ndef get_receivers(action):\r\n    if action == SendActionChoices.MAILING_LIST:\r\n        receivers = (\r\n            get_user_model()\r\n            .objects.filter(user_profile__receive_newsletter=True)\r\n            .order_by(\"pk\")\r\n        )\r\n    elif action == SendActionChoices.STAFF:\r\n        receivers = (\r\n            get_user_model().objects.filter(is_staff=True).order_by(\"pk\")\r\n        )\r\n    elif action == SendActionChoices.CHALLENGE_ADMINS:\r\n        receivers = (\r\n            get_user_model()\r\n            .objects.filter(\r\n                groups__admins_of_challenge__isnull=False,\r\n                user_profile__receive_newsletter=True,\r\n            )\r\n            .distinct()\r\n            .order_by(\"pk\")\r\n        )\r\n    elif action == SendActionChoices.READER_STUDY_EDITORS:\r\n        receivers = (\r\n            get_user_model()\r\n            .objects.filter(\r\n                groups__editors_of_readerstudy__isnull=False,\r\n                user_profile__receive_newsletter=True,\r\n            )\r\n            .distinct()\r\n            .order_by(\"pk\")\r\n        )\r\n    elif action == SendActionChoices.ALGORITHM_EDITORS:\r\n        receivers = (\r\n            get_user_model()\r\n            .objects.filter(\r\n                groups__editors_of_algorithm__isnull=False,\r\n                user_profile__receive_newsletter=True,\r\n            )\r\n            .distinct()\r\n            .order_by(\"pk\")\r\n        )\r\n\r\n    return receivers\r\n\r\n\r\ndef send_mass_html_email(datatuple):\r\n    connection = get_connection()\r\n    messages = []\r\n    for subject, message, sender, recipient, html in datatuple:\r\n        email = EmailMultiAlternatives(\r\n            subject, message, sender, recipient, connection=connection\r\n        )\r\n        email.attach_alternative(html, \"text/html\")\r\n        messages.append(email)\r\n    return connection.send_messages(messages)\r\n\r\n\r\n@shared_task(**settings.CELERY_TASK_DECORATOR_KWARGS[\"acks-late-micro-short\"])\r\ndef send_bulk_email(action, email_pk):\r\n    try:\r\n        email = Email.objects.filter(sent=False).get(pk=email_pk)\r\n    except ObjectDoesNotExist:\r\n        return\r\n    subject = email.subject\r\n    body = email.body\r\n    html_body = md2html(body)\r\n    receivers = get_receivers(action=action)\r\n    paginator = Paginator(receivers, 100)\r\n    site = Site.objects.get_current()\r\n    if email.status_report:\r\n        start_page = email.status_report[\"last_processed_batch\"]\r\n    else:\r\n        start_page = 0\r\n    for page_nr in paginator.page_range[start_page:]:\r\n        messages = []\r\n        for recipient in paginator.page(page_nr).object_list:\r\n            user = get_user_model().objects.get(pk=recipient.pk)\r\n            link = reverse(\r\n                \"profile-update\", kwargs={\"username\": user.username}\r\n            )\r\n            html_content = render_to_string(\r\n                \"vendor/mailgun_transactional_emails/action.html\",\r\n                {\r\n                    \"title\": subject,\r\n                    \"username\": user.username,\r\n                    \"content\": html_body,\r\n                    \"link\": link,\r\n                },\r\n            )\r\n            html_content_without_linebreaks = html_content.replace(\"\\n\", \"\")\r\n            text_content = strip_tags(html_content_without_linebreaks)\r\n            messages.append(\r\n                (\r\n                    f\"[{site.domain.lower()}] {subject}\",\r\n                    text_content,\r\n                    settings.DEFAULT_FROM_EMAIL,\r\n                    [user.email],\r\n                    html_content_without_linebreaks,\r\n                )\r\n            )\r\n        send_mass_html_email(messages)\r\n        email.status_report = {\"last_processed_batch\": page_nr}\r\n        email.save()\r\n\r\n    email.sent = True\r\n    email.sent_at = now()\r\n    email.status_report = None\r\n    email.save()\r\n", "path": "app/grandchallenge/emails/tasks.py"}], "after_files": [{"content": "from celery import shared_task\r\nfrom django.core.paginator import Paginator\r\nfrom django.utils.timezone import now\r\n\r\nfrom grandchallenge.notifications.emails import send_unread_notifications_email\r\nfrom grandchallenge.profiles.models import UserProfile\r\n\r\n\r\n@shared_task\r\ndef send_unread_notification_emails():\r\n    profiles = (\r\n        UserProfile.objects.filter(\r\n            receive_notification_emails=True,\r\n            user__notification__read=False,\r\n            user__is_active=True,\r\n        )\r\n        .distinct()\r\n        .prefetch_related(\"user__notification_set\")\r\n        .order_by(\"pk\")\r\n    )\r\n    paginator = Paginator(profiles, 1000)\r\n\r\n    for page_nr in paginator.page_range:\r\n        current_page_profiles = paginator.page(page_nr).object_list\r\n        current_time = now()\r\n        recipients = {}\r\n        for profile in current_page_profiles:\r\n            unread_notifications = [\r\n                n\r\n                for n in profile.user.notification_set.all()\r\n                if not n.read\r\n                and (\r\n                    profile.notification_email_last_sent_at is None\r\n                    or n.created > profile.notification_email_last_sent_at\r\n                )\r\n            ]\r\n            if unread_notifications:\r\n                recipients[profile] = len(unread_notifications)\r\n                profile.notification_email_last_sent_at = current_time\r\n\r\n        UserProfile.objects.bulk_update(\r\n            current_page_profiles, [\"notification_email_last_sent_at\"]\r\n        )\r\n        send_unread_notifications_email(recipients)\r\n", "path": "app/grandchallenge/notifications/tasks.py"}, {"content": "from celery import shared_task\r\nfrom django.conf import settings\r\nfrom django.contrib.auth import get_user_model\r\nfrom django.contrib.sites.models import Site\r\nfrom django.core.exceptions import ObjectDoesNotExist\r\nfrom django.core.mail import EmailMultiAlternatives, get_connection\r\nfrom django.core.paginator import Paginator\r\nfrom django.template.loader import render_to_string\r\nfrom django.utils.html import strip_tags\r\nfrom django.utils.timezone import now\r\n\r\nfrom grandchallenge.core.templatetags.bleach import md2html\r\nfrom grandchallenge.emails.models import Email\r\nfrom grandchallenge.emails.utils import SendActionChoices\r\nfrom grandchallenge.subdomains.utils import reverse\r\n\r\n\r\ndef get_receivers(action):\r\n    if action == SendActionChoices.MAILING_LIST:\r\n        receivers = (\r\n            get_user_model()\r\n            .objects.filter(\r\n                user_profile__receive_newsletter=True, is_active=True\r\n            )\r\n            .order_by(\"pk\")\r\n        )\r\n    elif action == SendActionChoices.STAFF:\r\n        receivers = (\r\n            get_user_model()\r\n            .objects.filter(is_staff=True, is_active=True)\r\n            .order_by(\"pk\")\r\n        )\r\n    elif action == SendActionChoices.CHALLENGE_ADMINS:\r\n        receivers = (\r\n            get_user_model()\r\n            .objects.filter(\r\n                groups__admins_of_challenge__isnull=False,\r\n                user_profile__receive_newsletter=True,\r\n                is_active=True,\r\n            )\r\n            .distinct()\r\n            .order_by(\"pk\")\r\n        )\r\n    elif action == SendActionChoices.READER_STUDY_EDITORS:\r\n        receivers = (\r\n            get_user_model()\r\n            .objects.filter(\r\n                groups__editors_of_readerstudy__isnull=False,\r\n                user_profile__receive_newsletter=True,\r\n                is_active=True,\r\n            )\r\n            .distinct()\r\n            .order_by(\"pk\")\r\n        )\r\n    elif action == SendActionChoices.ALGORITHM_EDITORS:\r\n        receivers = (\r\n            get_user_model()\r\n            .objects.filter(\r\n                groups__editors_of_algorithm__isnull=False,\r\n                user_profile__receive_newsletter=True,\r\n                is_active=True,\r\n            )\r\n            .distinct()\r\n            .order_by(\"pk\")\r\n        )\r\n\r\n    return receivers\r\n\r\n\r\ndef send_mass_html_email(datatuple):\r\n    connection = get_connection()\r\n    messages = []\r\n    for subject, message, sender, recipient, html in datatuple:\r\n        email = EmailMultiAlternatives(\r\n            subject, message, sender, recipient, connection=connection\r\n        )\r\n        email.attach_alternative(html, \"text/html\")\r\n        messages.append(email)\r\n    return connection.send_messages(messages)\r\n\r\n\r\n@shared_task(**settings.CELERY_TASK_DECORATOR_KWARGS[\"acks-late-micro-short\"])\r\ndef send_bulk_email(action, email_pk):\r\n    try:\r\n        email = Email.objects.filter(sent=False).get(pk=email_pk)\r\n    except ObjectDoesNotExist:\r\n        return\r\n    subject = email.subject\r\n    body = email.body\r\n    html_body = md2html(body)\r\n    receivers = get_receivers(action=action)\r\n    paginator = Paginator(receivers, 100)\r\n    site = Site.objects.get_current()\r\n    if email.status_report:\r\n        start_page = email.status_report[\"last_processed_batch\"]\r\n    else:\r\n        start_page = 0\r\n    for page_nr in paginator.page_range[start_page:]:\r\n        messages = []\r\n        for recipient in paginator.page(page_nr).object_list:\r\n            user = get_user_model().objects.get(pk=recipient.pk)\r\n            link = reverse(\r\n                \"profile-update\", kwargs={\"username\": user.username}\r\n            )\r\n            html_content = render_to_string(\r\n                \"vendor/mailgun_transactional_emails/action.html\",\r\n                {\r\n                    \"title\": subject,\r\n                    \"username\": user.username,\r\n                    \"content\": html_body,\r\n                    \"link\": link,\r\n                },\r\n            )\r\n            html_content_without_linebreaks = html_content.replace(\"\\n\", \"\")\r\n            text_content = strip_tags(html_content_without_linebreaks)\r\n            messages.append(\r\n                (\r\n                    f\"[{site.domain.lower()}] {subject}\",\r\n                    text_content,\r\n                    settings.DEFAULT_FROM_EMAIL,\r\n                    [user.email],\r\n                    html_content_without_linebreaks,\r\n                )\r\n            )\r\n        send_mass_html_email(messages)\r\n        email.status_report = {\"last_processed_batch\": page_nr}\r\n        email.save()\r\n\r\n    email.sent = True\r\n    email.sent_at = now()\r\n    email.status_report = None\r\n    email.save()\r\n", "path": "app/grandchallenge/emails/tasks.py"}]}