From f70835b996216cfee7febe21a5c62d7b0849acce Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Bedna=C5=99=C3=ADk?= <jan.bednarik@gmail.com>
Date: Mon, 15 May 2023 04:03:01 +0200
Subject: [PATCH] Subscribe to newsletters in Mailtrain

---
 README.md                     |  2 ++
 czech_inspirational/models.py |  4 +---
 elections2021/models.py       |  4 +---
 main/models.py                | 37 ++++++++++-------------------------
 majak/settings/base.py        | 21 +++++++-------------
 shared/utils.py               | 18 ++++++-----------
 6 files changed, 27 insertions(+), 59 deletions(-)

diff --git a/README.md b/README.md
index 0b4ba971..657476c1 100644
--- a/README.md
+++ b/README.md
@@ -157,6 +157,8 @@ Různé:
 | `SENTRY_DSN` | | pokud je zadáno, pády se reportují do Sentry |
 | `SEARCH_CONFIG` | english | nastavení jazyka fulltextového vyhledávání, viz níže |
 | `DEBUG_TOOLBAR` | False | zobrazit Django Debug Toolbar (pro vývoj) |
+| `MAILTRAIN_API_URL` | | URL k API Mailtrain |
+| `MAILTRAIN_API_TOKEN` | | token k API Mailtrain |
 
 Settings pro appky na weby:
 
diff --git a/czech_inspirational/models.py b/czech_inspirational/models.py
index e7c33cbd..b92889df 100644
--- a/czech_inspirational/models.py
+++ b/czech_inspirational/models.py
@@ -299,9 +299,7 @@ class CzechInspirationalDownloadPage(
                     pass
                 else:
                     subscribe_to_newsletter(
-                        email,
-                        settings.CZECH_INSPIRATIONAL_NEWSLETTER_ID,
-                        settings.CZECH_INSPIRATIONAL_NEWSLETTER_SOURCE,
+                        email, settings.CZECH_INSPIRATIONAL_NEWSLETTER_CID
                     )
 
         return context
diff --git a/elections2021/models.py b/elections2021/models.py
index cd452b16..dc170d52 100644
--- a/elections2021/models.py
+++ b/elections2021/models.py
@@ -518,9 +518,7 @@ class Elections2021HomePage(MetadataPageMixin, RoutablePageMixin, Page):
             form = SubscribeForm(request.POST)
             if form.is_valid():
                 subscribe_to_newsletter(
-                    form.cleaned_data["email"],
-                    settings.ELECTIONS2021_NEWSLETTER_ID,
-                    settings.ELECTIONS2021_NEWSLETTER_SOURCE,
+                    form.cleaned_data["email"], settings.ELECTIONS2021_NEWSLETTER_CID
                 )
                 try:
                     page = (
diff --git a/main/models.py b/main/models.py
index 26535bfa..4bf2a0b6 100644
--- a/main/models.py
+++ b/main/models.py
@@ -298,9 +298,7 @@ class MainHomePage(
             form = SubscribeForm(request.POST)
             if form.is_valid():
                 subscribe_to_newsletter(
-                    form.cleaned_data["email"],
-                    settings.PIRATICZ_NEWSLETTER_ID,
-                    settings.PIRATICZ_NEWSLETTER_SOURCE,
+                    form.cleaned_data["email"], settings.PIRATICZ_NEWSLETTER_CID
                 )
 
                 messages.success(
@@ -491,19 +489,13 @@ class MainArticlesPage(
 
     def get_all_articles_search_response(self, request):
         article_paginator = Paginator(
-            MainArticlePage
-            .objects
-            .order_by("-date")
-            .live()
-            .search(request.GET["q"]),
+            MainArticlePage.objects.order_by("-date").live().search(request.GET["q"]),
             10,
         )
         article_page = article_paginator.get_page(request.GET.get("page", 1))
         context = {"article_data_list": article_page.object_list}
         html_content = render(
-            request,
-            "main/includes/person_article_preview.html",
-            context
+            request, "main/includes/person_article_preview.html", context
         ).content
         data = {
             "html": html_content.decode("utf-8"),
@@ -519,16 +511,11 @@ class MainArticlesPage(
     def search(self, request):
         if request.method == "GET" and "q" in request.GET:
             query = request.GET["q"]
-            
+
             article_results = (
-                MainArticlePage
-                .objects
-                .order_by("-date")
-                .live()
-                .search(query)
-                [:11]
+                MainArticlePage.objects.order_by("-date").live().search(query)[:11]
             )
-            
+
             return render(
                 request,
                 "main/main_article_search.html",
@@ -537,8 +524,8 @@ class MainArticlesPage(
                     "query": query,
                     "article_results": article_results[:10],
                     "show_more_articles": len(article_results) > 10,
-                    "sub_heading": f"Vyhledávání „{query}“"
-                }
+                    "sub_heading": f"Vyhledávání „{query}“",
+                },
             )
         else:
             return HttpResponseRedirect(self.url)
@@ -962,9 +949,7 @@ class MainCrossroadPage(
         verbose_name = "RozcestnĂ­k s kartami"
 
 
-class MainHoaxPage(
-    ExtendedMetadataPageMixin, SubpageMixin, MetadataPageMixin, Page
-):
+class MainHoaxPage(ExtendedMetadataPageMixin, SubpageMixin, MetadataPageMixin, Page):
     ### FIELDS
 
     description = RichTextField(
@@ -974,9 +959,7 @@ class MainHoaxPage(
     )
 
     content = StreamField(
-        [
-            (("hoax"), blocks.HoaxBlock())
-        ],
+        [(("hoax"), blocks.HoaxBlock())],
         verbose_name="Hoaxy a jejich vysvětlení",
         blank=True,
         use_json_field=True,
diff --git a/majak/settings/base.py b/majak/settings/base.py
index 80b8a324..aa917865 100644
--- a/majak/settings/base.py
+++ b/majak/settings/base.py
@@ -284,24 +284,17 @@ DONATE_PORTAL_API_URL = env.str("DONATE_PORTAL_API_URL", default="")
 DONATE_PORTAL_API_TIMEOUT = 5
 DONATE_PORTAL_API_CACHE_TIMEOUT = 60 * 5
 
-CZECH_INSPIRATIONAL_NEWSLETTER_ID = env.int(
-    "CZECH_INSPIRATIONAL_NEWSLETTER_ID", default=0
-)
-CZECH_INSPIRATIONAL_NEWSLETTER_SOURCE = env.str(
-    "CZECH_INSPIRATIONAL_NEWSLETTER_SOURCE", default="ÄŚesko inspirativnĂ­"
-)
+MAILTRAIN_API_URL = env.str("MAILTRAIN_API_URL", default="")
+MAILTRAIN_API_TOKEN = env.str("MAILTRAIN_API_TOKEN", default="")
 
-NALODENI_API_NEWS_SUBSCRIBE_URL = env.str("NALODENI_API_NEWS_SUBSCRIBE_URL", default="")
-NALODENI_API_CREDENTIALS = env.str("NALODENI_API_CREDENTIALS", default="")
+CZECH_INSPIRATIONAL_NEWSLETTER_CID = env.str(
+    "CZECH_INSPIRATIONAL_NEWSLETTER_CID", default=""
+)
 
 ELECTIONS2021_COOKIE_NAME = "program"
-ELECTIONS2021_NEWSLETTER_ID = env.int("ELECTIONS2021_NEWSLETTER_ID", default=0)
-ELECTIONS2021_NEWSLETTER_SOURCE = env.str(
-    "ELECTIONS2021_NEWSLETTER_SOURCE", "Koalice 2021"
-)
+ELECTIONS2021_NEWSLETTER_CID = env.str("ELECTIONS2021_NEWSLETTER_CID", default="")
 
-PIRATICZ_NEWSLETTER_ID = env.int("PIRATICZ_NEWSLETTER_ID", default=0)
-PIRATICZ_NEWSLETTER_SOURCE = env.str("PIRATICZ_NEWSLETTER_SOURCE", "Piráti.cz")
+PIRATICZ_NEWSLETTER_CID = env.str("PIRATICZ_NEWSLETTER_CID", default="")
 
 # URL pointing to MapProxy instance to use.
 # MapProxy is used to serve map tiles to hide client details from the tile provider.
diff --git a/shared/utils.py b/shared/utils.py
index c2a42ee8..48a1cc32 100644
--- a/shared/utils.py
+++ b/shared/utils.py
@@ -1,6 +1,7 @@
 import json
 import logging
 import urllib.request
+from urllib.parse import urljoin
 
 import bleach
 import requests
@@ -53,22 +54,15 @@ def make_promote_panels(
     return [MultiFieldPanel(panels, gettext_lazy("Common page configuration"))]
 
 
-def subscribe_to_newsletter(email, news_id, source):
-    payload = {
-        "email": email,
-        "news_id": news_id,
-        "source": source,
-        "verify_email": 1,
-    }
+def subscribe_to_newsletter(email, list_id):
+    url = urljoin(settings.MAILTRAIN_API_URL, f"subscribe/{list_id}")
+    data = {"EMAIL": email, "FORCE_SUBSCRIBE": False, "REQUIRE_CONFIRMATION": True}
     response = requests.post(
-        settings.NALODENI_API_NEWS_SUBSCRIBE_URL,
-        data=json.dumps(payload),
-        auth=tuple(settings.NALODENI_API_CREDENTIALS.split(":")),
+        url, data=data, headers={"access-token": settings.MAILTRAIN_API_TOKEN}
     )
     if response.status_code != 200:
         logger.error(
-            "Failed to subscribe!",
-            extra={"payload": payload, "response": response.text},
+            "Failed to subscribe!", extra={"data": data, "response": response.text}
         )
 
 
-- 
GitLab