From bbf8cc19a53b3436c955c3f4f7e47ce13ed4f734 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Valenta?= <git@imaniti.org>
Date: Wed, 19 Jul 2023 19:31:05 +0900
Subject: [PATCH] remove Instagram

---
 README.md                                     |  2 -
 main/blocks.py                                | 21 ------
 ..._mainhomepage_instagram_access_and_more.py | 30 +++++++++
 main/models.py                                | 66 -------------------
 .../main/blocks/instagram_block.html          | 49 --------------
 .../main/includes/instagram_widget.html       | 40 -----------
 majak/settings/base.py                        |  8 ---
 7 files changed, 30 insertions(+), 186 deletions(-)
 create mode 100644 main/migrations/0058_remove_mainhomepage_instagram_access_and_more.py
 delete mode 100644 main/templates/main/blocks/instagram_block.html
 delete mode 100644 main/templates/main/includes/instagram_widget.html

diff --git a/README.md b/README.md
index 32c96ece..50f9cdaa 100644
--- a/README.md
+++ b/README.md
@@ -167,8 +167,6 @@ Settings pro appky na weby:
 | `DONATE_PORTAL_REDIRECT_URL` | "" | URL pro přesměrování z darovacího formuláře |
 | `DONATE_PORTAL_REDIRECT_SOURCE` | dary.pirati.cz | identifikátor zdroje pro přesměrování na darovací portál |
 | `DONATE_PORTAL_API_URL` | "" | URL s API darovacího portálu |
-| `INSTAGRAM_USERNAME` | "" | Login username pro Instagram sync |
-| `INSTAGRAM_SESSION` | "" | Login session pro Instagram sync |
 
 ### Management commands
 
diff --git a/main/blocks.py b/main/blocks.py
index 5e2ef662..d0d0c48b 100644
--- a/main/blocks.py
+++ b/main/blocks.py
@@ -360,27 +360,6 @@ class CardLinkWithHeadlineBlock(CardLinkWithHeadlineBlockMixin):
         label = "Karty odkazů s nadpisem"
 
 
-class InstagramAccessBlock(StructBlock):
-    username = CharBlock(
-        label="Uživatelské jméno", help_text="Např. pirati.cz, bez @ na začátku!"
-    )
-
-    class Meta:
-        label = "Synchronizace s Instagramem"
-
-
-class InstagramPostsBlock(StructBlock):
-    title = CharBlock(
-        label="Titulek",
-        help_text="Instagramové posty budou načteny pro všechny profily uvedené v nastavení webu automaticky",
-    )
-
-    class Meta:
-        template = "main/blocks/instagram_block.html"
-        icon = "openquote"
-        label = "Instagramové posty"
-
-
 class HoaxBlock(StructBlock):
     title = CharBlock(label="Titulek")
     hoax = RichTextBlock(label="Hoax")
diff --git a/main/migrations/0058_remove_mainhomepage_instagram_access_and_more.py b/main/migrations/0058_remove_mainhomepage_instagram_access_and_more.py
new file mode 100644
index 00000000..e1db51aa
--- /dev/null
+++ b/main/migrations/0058_remove_mainhomepage_instagram_access_and_more.py
@@ -0,0 +1,30 @@
+# Generated by Django 4.1.10 on 2023-07-19 10:30
+
+from django.db import migrations
+import main.blocks
+import wagtail.blocks
+import wagtail.fields
+import wagtail.images.blocks
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('main', '0057_remove_mainpersonpage_instagram_access_and_more'),
+    ]
+
+    operations = [
+        migrations.RemoveField(
+            model_name='mainhomepage',
+            name='instagram_access',
+        ),
+        migrations.RemoveField(
+            model_name='mainpersonpage',
+            name='instagram_username',
+        ),
+        migrations.AlterField(
+            model_name='mainhomepage',
+            name='content',
+            field=wagtail.fields.StreamField([('carousel', wagtail.blocks.StructBlock([('slides', wagtail.blocks.ListBlock(main.blocks.HomePageCarouseSlideBlock, label='Obrázky s nadpisy - carouselu'))])), ('news', wagtail.blocks.StructBlock([('title', wagtail.blocks.CharBlock(help_text='Nejnovější články se načtou automaticky', label='Titulek')), ('image', wagtail.images.blocks.ImageChooserBlock(label='Obrázek pozadí', required=False))])), ('people', wagtail.blocks.StructBlock([('title', wagtail.blocks.CharBlock(label='Hlavní titulek')), ('list', wagtail.blocks.ListBlock(main.blocks.BoxBlock, label='Boxíky'))])), ('regions', wagtail.blocks.StructBlock([('title', wagtail.blocks.CharBlock(help_text='Články pro regiony se načtou automaticky', label='Titulek')), ('image', wagtail.images.blocks.ImageChooserBlock(label='Obrázek pozadí', required=False))])), ('boxes', wagtail.blocks.StructBlock([('title', wagtail.blocks.CharBlock(label='Nadpis')), ('list', wagtail.blocks.ListBlock(main.blocks.BoxBlock, label='Boxíky')), ('image', wagtail.images.blocks.ImageChooserBlock(label='Obrázek pozadí', required=False))]))], blank=True, use_json_field=True, verbose_name='Hlavní obsah'),
+        ),
+    ]
diff --git a/main/models.py b/main/models.py
index cbb69fe9..9ef5b8b3 100644
--- a/main/models.py
+++ b/main/models.py
@@ -31,7 +31,6 @@ from wagtailmetadata.models import MetadataPageMixin
 
 from calendar_utils.models import CalendarMixin
 from elections2021.constants import REGION_CHOICES  # pozor, import ze sousedního modulu
-from instagram_utils.models import InstagramMixin, InstagramPost
 from shared.forms import SubscribeForm
 from shared.models import (  # MenuMixin,
     ArticleMixin,
@@ -58,7 +57,6 @@ class MainHomePage(
     RoutablePageMixin,
     ExtendedMetadataHomePageMixin,
     MetadataPageMixin,
-    InstagramMixin,
     Page,
 ):
     # header
@@ -96,7 +94,6 @@ class MainHomePage(
             ("news", blocks.NewsBlock()),
             ("people", blocks.PeopleOverviewBlock()),
             ("regions", blocks.RegionsBlock()),
-            ("instagram_posts", blocks.InstagramPostsBlock()),
             ("boxes", blocks.BoxesBlock()),
         ],
         verbose_name="Hlavní obsah",
@@ -144,14 +141,6 @@ class MainHomePage(
         use_json_field=True,
     )
 
-    instagram_access = StreamField(
-        [("instagram_access", blocks.InstagramAccessBlock())],
-        verbose_name="Uživatelská jména synchronizovaných Instagram účtů",
-        blank=True,
-        max_num=64,
-        use_json_field=True,
-    )
-
     content_panels = Page.content_panels + [
         FieldPanel("content"),
         FieldPanel("footer_other_links"),
@@ -168,7 +157,6 @@ class MainHomePage(
         FieldPanel("donation_page_text"),
         FieldPanel("social_links"),
         FieldPanel("matomo_id"),
-        FieldPanel("instagram_access"),
     ]
 
     ### EDIT HANDLERS
@@ -213,18 +201,6 @@ class MainHomePage(
     def get_context(self, request, *args, **kwargs):
         context = super().get_context(request, args, kwargs)
 
-        instagram_username_list = [
-            access_data["value"]["username"]
-            for access_data in self.instagram_access.raw_data
-        ]
-
-        instagram_post_list = InstagramPost.objects.filter(
-            author_username__in=instagram_username_list
-        ).order_by("-timestamp")
-
-        context["instagram_post_list"] = instagram_post_list[:3]
-        context["show_next_instagram_post"] = len(instagram_post_list) > 3
-
         context["regions"] = REGION_CHOICES
 
         context["article_data_list"] = (
@@ -262,40 +238,10 @@ class MainHomePage(
         }
         return JsonResponse(data=data, safe=False)
 
-    def get_instagram_response(self, request):
-        instagram_username_list = [
-            access_data["value"]["username"]
-            for access_data in self.instagram_access.raw_data
-        ]
-
-        instagram_post_list_queryset = InstagramPost.objects.filter(
-            author_username__in=instagram_username_list
-        ).order_by("-timestamp")
-
-        instagram_post_paginator = Paginator(instagram_post_list_queryset, 3)
-
-        instagram_post_page = instagram_post_paginator.get_page(
-            request.GET.get("page", 1)
-        )
-        context = {"instagram_post_list": instagram_post_page.object_list}
-
-        html_content = render(
-            request, "main/includes/instagram_widget.html", context
-        ).content
-
-        data = {
-            "html": html_content.decode("utf-8"),
-            "has_next": instagram_post_page.has_next(),
-        }
-
-        return JsonResponse(data=data, safe=False)
-
     def serve(self, request, *args, **kwargs):
         if request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest":
             if "region" in request.GET:
                 return self.get_region_response(request)
-            else:
-                return self.get_instagram_response(request)
 
         return super().serve(request, *args, **kwargs)
 
@@ -769,10 +715,6 @@ class MainPersonPage(
     perex = models.TextField()
     text = RichTextField()
 
-    instagram_username = models.CharField(
-        "Uživatelské jméno na Instagramu", max_length=64, blank=True, null=True
-    )
-
     social_links = StreamField(
         [
             ("social_links", blocks.SocialLinkBlock()),
@@ -811,7 +753,6 @@ class MainPersonPage(
         FieldPanel("email"),
         FieldPanel("phone"),
         FieldPanel("calendar_url"),
-        FieldPanel("instagram_username"),
         FieldPanel("social_links"),
         FieldPanel("people"),
     ]
@@ -819,13 +760,6 @@ class MainPersonPage(
     def get_context(self, request) -> dict:
         context = super().get_context(request)
 
-        if self.instagram_username:
-            context["instagram_post_list"] = (
-                InstagramPost.objects.filter(
-                    author_username=self.instagram_username
-                ).order_by("-timestamp")
-            )[:20]
-
         context["article_page_list"] = MainArticlePage.objects.filter(
             author_page=self.id
         )
diff --git a/main/templates/main/blocks/instagram_block.html b/main/templates/main/blocks/instagram_block.html
deleted file mode 100644
index 63c01f6e..00000000
--- a/main/templates/main/blocks/instagram_block.html
+++ /dev/null
@@ -1,49 +0,0 @@
-<div class="container--wide mx-auto mb-8 lg:mb-16">
-  <div class="flex flex-wrap justify-center items-center">
-    <h2 class="w-full head-7xl xl:text-center mb-6 xl:mb-28">
-      {{ self.title }}
-    </h2>
-  </div>
-  <ul class="flex flex-wrap justify-center gap-3" id="instagram-posts-list">
-    {% include 'main/includes/instagram_widget.html' with instagram_post_list=instagram_post_list %}
-  </ul>
-  {% if show_next_instagram_post %}
-    <div class="flex justify-center mt-8 lg:mt-24">
-      <a
-        onclick="showMorePosts(event, this)"
-        href="#"
-        data-url="{{ page_url }}?page="
-        data-page="2"
-        class="btn btn--black btn--to-yellow-500 btn--hoveractive uppercase"
-      >
-        <span class="btn__body-wrap">
-          <span class="btn__body text-lg lg:text-base">
-            Zobrazit starší
-          </span>
-        </span>
-      </a>
-    </div>
-  {% endif %}
-</div>
-
-<script type="text/javascript">
-  async function showMorePosts(event, btn) {
-    event.preventDefault()
-    const postList = document.getElementById("instagram-posts-list");
-
-    const url = btn.getAttribute("data-url") + btn.getAttribute("data-page")
-    const response = await fetch(url, {
-      method: "GET",
-      headers: {
-        "X-Requested-With": "XMLHttpRequest",
-      },
-    })
-    const data = await response.json()
-
-    postList.innerHTML += data.html;
-    if (!data.has_next) { btn.style.display = "none"; }
-
-    const dataPage = parseInt(btn.getAttribute("data-page")) + 1
-    btn.setAttribute("data-page", dataPage)
-  }
-</script>
diff --git a/main/templates/main/includes/instagram_widget.html b/main/templates/main/includes/instagram_widget.html
deleted file mode 100644
index a443eb22..00000000
--- a/main/templates/main/includes/instagram_widget.html
+++ /dev/null
@@ -1,40 +0,0 @@
-{% for post in instagram_post_list %}
-  <li class="flex max-w-sm max-w-xs w-full h-[20rem]">
-    <a
-      href="{{ post.url }}"
-      class="group h-full w-full flex flex-col align-center overflow-hidden text-center border border-grey-100 relative hover:no-underline"
-    >
-      <div class="md:min-h-[20rem] p-4 opacity-0 group-focus:opacity-100 group-hover:opacity-100 duration-150 z-10">
-        <div class="flex flex-col items-center">
-          <div class="mb-4 flex items-center justify-between xl:flex-col gap-3">
-            <div class="flex flex-col">
-              <h5 class="font-alt text-xl mt-3 mb-1 text-left sm:text-center">
-                {{ post.author_name }}
-              </h5>
-              <small class="text-brands-instagram text-left sm:text-center">
-                @{{ post.author_username }}
-              </small>
-            </div>
-          </div>
-          <p class="text-small sm:text-base leading-6 mb-2">
-            {{ post.caption }}
-          </p>
-        </div>
-      </div>
-
-      <div class="absolute inset-0 flex-shrink-0 z-0 duration-150 group-focus:blur-lg group-focus:opacity-25 group-hover:blur-lg group-hover:opacity-25">
-        <div class="relative">
-          <div class="absolute left-4 top-4 bg-white rounded-lg p-1.5 drop-shadow-md">
-            <i class="ico--instagram text-brands-instagram text-2xl"></i>
-          </div>
-
-          <img
-            class="h-[20rem] object-cover"
-            src="{{ post.image.url }}"
-            alt="Obrázek v Instagramovém postu, popis „{{ post.caption }}“"
-          >
-        </div>
-      </div>
-    </a>
-  </li>
-{% endfor %}
diff --git a/majak/settings/base.py b/majak/settings/base.py
index 2184834e..4542b8db 100644
--- a/majak/settings/base.py
+++ b/majak/settings/base.py
@@ -48,7 +48,6 @@ INSTALLED_APPS = [
     "calendar_utils",
     "maps_utils",
     "redmine_utils",
-    "instagram_utils",
     "users",
     "pirates",
     "tuning",
@@ -308,10 +307,3 @@ MAPS_UTILS_MAPPROXY_URL = env.str(
 )
 
 TWITTER_BEARER_TOKEN = env.str("TWITTER_BEARER_TOKEN", default="")
-
-INSTAGRAM_USERNAME = env.str("INSTAGRAM_USERNAME", default="")
-
-raw_instagram_session = env.str("INSTAGRAM_SESSION", default="")
-INSTAGRAM_SESSION = (
-    json.loads(raw_instagram_session) if raw_instagram_session != "" else None
-)
-- 
GitLab