Repository: uccser/cs-unplugged

Issue:
Printable thumbnails should display in current website language
This also includes printable thumbnails on the printable list page.


Discussion:

Resolving patch:
diff --git a/csunplugged/config/context_processors/deployed.py b/csunplugged/config/context_processors/deployed.py
--- a/csunplugged/config/context_processors/deployed.py
+++ b/csunplugged/config/context_processors/deployed.py
@@ -1,6 +1,6 @@
 """Context processor for checking if in deployed environment."""
 
-import environ
+from django.conf import settings
 
 
 def deployed(request):
@@ -9,7 +9,6 @@ def deployed(request):
     Returns:
         Dictionary containing deployed boolean to add to context.
     """
-    env = environ.Env()
     return {
-        "DEPLOYED": env.bool("DJANGO_PRODUCTION", False)
+        "DEPLOYED": settings.DJANGO_PRODUCTION
     }
diff --git a/csunplugged/resources/management/commands/makeresourcethumbnails.py b/csunplugged/resources/management/commands/makeresourcethumbnails.py
--- a/csunplugged/resources/management/commands/makeresourcethumbnails.py
+++ b/csunplugged/resources/management/commands/makeresourcethumbnails.py
@@ -4,6 +4,7 @@
 import os.path
 from urllib.parse import urlencode
 from tqdm import tqdm
+from django.conf import settings
 from django.core.management.base import BaseCommand
 from django.http.request import QueryDict
 from django.utils import translation
@@ -13,7 +14,7 @@
 from utils.bool_to_yes_no import bool_to_yes_no
 from resources.utils.resource_parameters import EnumResourceParameter
 
-BASE_PATH_TEMPLATE = "build/img/resources/{resource}/thumbnails/"
+BASE_PATH_TEMPLATE = "build/img/resources/{resource}/thumbnails/{language}"
 
 
 class Command(BaseCommand):
@@ -25,34 +26,43 @@ def handle(self, *args, **options):
         """Automatically called when makeresourcethumbnails command is given."""
         resources = Resource.objects.order_by("name")
 
-        with translation.override("en"):
-            for resource in resources:
-                base_path = BASE_PATH_TEMPLATE.format(resource=resource.slug)
-                if not os.path.exists(base_path):
-                    os.makedirs(base_path)
-
-                # TODO: Import repeated in next for loop, check alternatives
-                empty_generator = get_resource_generator(resource.generator_module)
-
-                if not all([isinstance(option, EnumResourceParameter)
-                            for option in empty_generator.get_options().values()]):
-                    raise TypeError("Only EnumResourceParameters are supported for pre-generation")
-                valid_options = {option.name: list(option.valid_values.keys())
-                                 for option in empty_generator.get_options().values()}
-                combinations = resource_valid_configurations(valid_options)
-
-                # Create thumbnail for all possible combinations
-                print("Creating thumbnails for {}".format(resource.name))
-                progress_bar = tqdm(combinations, ascii=True)
-
-                for combination in progress_bar:
-                    requested_options = QueryDict(urlencode(combination, doseq=True))
-                    generator = get_resource_generator(resource.generator_module, requested_options)
-
-                    filename = resource.slug + "-"
-                    for (key, value) in sorted(combination.items()):
-                        filename += "{}-{}-".format(key, bool_to_yes_no(value))
-                    filename = "{}.png".format(filename[:-1])
-                    thumbnail_file_path = os.path.join(base_path, filename)
-
-                    generator.save_thumbnail(resource.name, thumbnail_file_path)
+        if settings.DJANGO_PRODUCTION:
+            languages = settings.DEFAULT_LANGUAGES
+        else:
+            languages = [("en", "")]
+        for language_code, _ in languages:
+            with translation.override(language_code):
+                print("Creating thumbnails for language '{}''".format(language_code))
+                for resource in resources:
+                    base_path = BASE_PATH_TEMPLATE.format(
+                        resource=resource.slug,
+                        language=language_code
+                    )
+                    if not os.path.exists(base_path):
+                        os.makedirs(base_path)
+
+                    # TODO: Import repeated in next for loop, check alternatives
+                    empty_generator = get_resource_generator(resource.generator_module)
+
+                    if not all([isinstance(option, EnumResourceParameter)
+                                for option in empty_generator.get_options().values()]):
+                        raise TypeError("Only EnumResourceParameters are supported for pre-generation")
+                    valid_options = {option.name: list(option.valid_values.keys())
+                                     for option in empty_generator.get_options().values()}
+                    combinations = resource_valid_configurations(valid_options)
+
+                    # Create thumbnail for all possible combinations
+                    print("Creating thumbnails for {}".format(resource.name))
+                    progress_bar = tqdm(combinations, ascii=True)
+
+                    for combination in progress_bar:
+                        requested_options = QueryDict(urlencode(combination, doseq=True))
+                        generator = get_resource_generator(resource.generator_module, requested_options)
+
+                        filename = resource.slug + "-"
+                        for (key, value) in sorted(combination.items()):
+                            filename += "{}-{}-".format(key, bool_to_yes_no(value))
+                        filename = "{}.png".format(filename[:-1])
+                        thumbnail_file_path = os.path.join(base_path, filename)
+
+                        generator.save_thumbnail(resource.name, thumbnail_file_path)
diff --git a/csunplugged/resources/views.py b/csunplugged/resources/views.py
--- a/csunplugged/resources/views.py
+++ b/csunplugged/resources/views.py
@@ -1,10 +1,12 @@
 """Views for the resource application."""
 
+from os.path import join
 from urllib.parse import quote
 from django.conf import settings
 from django.http import HttpResponse, Http404
 from django.shortcuts import get_object_or_404, render
 from django.views import generic
+from django.utils.translation import get_language
 from resources.models import Resource
 from resources.utils.resource_pdf_cache import resource_pdf_cache
 from resources.utils.get_options_html import get_options_html
@@ -49,7 +51,20 @@ def resource(request, resource_slug):
     context["options_html"] = get_options_html(generator.get_options(), generator.get_local_options(), request.GET)
     context["resource"] = resource
     context["debug"] = settings.DEBUG
-    context["resource_thumbnail_base"] = "{}img/resources/{}/thumbnails/".format(settings.STATIC_URL, resource.slug)
+    if settings.DJANGO_PRODUCTION:
+        resource_language = get_language()
+        if resource_language in settings.INCONTEXT_L10N_PSEUDOLANGUAGES:
+            resource_language = "en"
+    else:
+        resource_language = "en"
+    context["resource_thumbnail_base"] = join(
+        settings.STATIC_URL,
+        "img/resources/",
+        resource.slug,
+        "thumbnails",
+        resource_language,
+        ""
+    )
     context["grouped_lessons"] = group_lessons_by_age(resource.lessons.all())
     context["copies_amount"] = settings.RESOURCE_COPY_AMOUNT
     if resource.thumbnail_static_path:


Test patch:
diff --git a/csunplugged/tests/resources/management/test_makeresourcethumbnails_command.py b/csunplugged/tests/resources/management/test_makeresourcethumbnails_command.py
--- a/csunplugged/tests/resources/management/test_makeresourcethumbnails_command.py
+++ b/csunplugged/tests/resources/management/test_makeresourcethumbnails_command.py
@@ -2,6 +2,7 @@
 
 from tests.BaseTestWithDB import BaseTestWithDB
 from django.core import management
+from django.conf import settings
 from django.test import tag, override_settings
 from tests.resources.ResourcesTestDataGenerator import ResourcesTestDataGenerator
 
@@ -14,7 +15,7 @@ def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
         self.test_data = ResourcesTestDataGenerator()
         self.language = "en"
-        self.THUMBNAIL_PATH = "build/img/resources/{}/thumbnails/{}"
+        self.THUMBNAIL_PATH = "build/img/resources/{}/thumbnails/{}/{}"
 
     def test_makeresourcethumbnails_command_single_resource(self):
         self.test_data.create_resource(
@@ -25,8 +26,8 @@ def test_makeresourcethumbnails_command_single_resource(self):
         )
         # TODO: Fix these tests, they shouldn't be writing files into the build directory
         management.call_command("makeresourcethumbnails")
-        open(self.THUMBNAIL_PATH.format("resource1", "resource1-paper_size-a4.png"))
-        open(self.THUMBNAIL_PATH.format("resource1", "resource1-paper_size-letter.png"))
+        open(self.THUMBNAIL_PATH.format("resource1", self.language, "resource1-paper_size-a4.png"))
+        open(self.THUMBNAIL_PATH.format("resource1", self.language, "resource1-paper_size-letter.png"))
 
     def test_makeresourcethumbnails_command_multiple_resources(self):
         self.test_data.create_resource(
@@ -43,10 +44,10 @@ def test_makeresourcethumbnails_command_multiple_resources(self):
         )
         # TODO: Fix these tests, they shouldn't be writing files into the build directory
         management.call_command("makeresourcethumbnails")
-        open(self.THUMBNAIL_PATH.format("resource1", "resource1-paper_size-a4.png"))
-        open(self.THUMBNAIL_PATH.format("resource1", "resource1-paper_size-letter.png"))
-        open(self.THUMBNAIL_PATH.format("resource2", "resource2-paper_size-a4.png"))
-        open(self.THUMBNAIL_PATH.format("resource2", "resource2-paper_size-letter.png"))
+        open(self.THUMBNAIL_PATH.format("resource1", self.language, "resource1-paper_size-a4.png"))
+        open(self.THUMBNAIL_PATH.format("resource1", self.language, "resource1-paper_size-letter.png"))
+        open(self.THUMBNAIL_PATH.format("resource2", self.language, "resource2-paper_size-a4.png"))
+        open(self.THUMBNAIL_PATH.format("resource2", self.language, "resource2-paper_size-letter.png"))
 
     def test_makeresourcethumbnails_command_resource_generator_has_non_enum_options(self):
         self.test_data.create_resource(
@@ -57,3 +58,17 @@ def test_makeresourcethumbnails_command_resource_generator_has_non_enum_options(
         )
         with self.assertRaises(TypeError):
             management.call_command("makeresourcethumbnails")
+
+    @override_settings(DJANGO_PRODUCTION=True)
+    def test_makeresourcethumbnails_command_single_resource_multiple_languages(self):
+        self.test_data.create_resource(
+            "resource1",
+            "Resource 1",
+            "Description of resource 1",
+            "BareResourceGenerator",
+        )
+        management.call_command("makeresourcethumbnails")
+        for language_code, _ in settings.PRODUCTION_LANGUAGES:
+            if language_code not in settings.INCONTEXT_L10N_PSEUDOLANGUAGES:
+                open(self.THUMBNAIL_PATH.format("resource1", language_code, "resource1-paper_size-a4.png"))
+                open(self.THUMBNAIL_PATH.format("resource1", language_code, "resource1-paper_size-letter.png"))
diff --git a/csunplugged/tests/resources/views/test_resource_view.py b/csunplugged/tests/resources/views/test_resource_view.py
--- a/csunplugged/tests/resources/views/test_resource_view.py
+++ b/csunplugged/tests/resources/views/test_resource_view.py
@@ -1,12 +1,19 @@
 from http import HTTPStatus
-from django.test import tag
+from django.conf import settings
+from django.test import tag, override_settings
 from django.urls import reverse
+from django.utils import translation
 from tests.BaseTestWithDB import BaseTestWithDB
 from tests.resources.ResourcesTestDataGenerator import ResourcesTestDataGenerator
 from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator
 from topics.models import ResourceDescription
 from collections import OrderedDict
 
+MULTIPLE_LANGUAGES_WITH_INCONTEXT = (
+    *settings.LANGUAGES,
+    (settings.INCONTEXT_L10N_PSEUDOLANGUAGE, settings.INCONTEXT_L10N_PSEUDOLANGUAGE)
+)
+
 
 @tag("resource")
 class ResourceViewTest(BaseTestWithDB):
@@ -61,16 +68,71 @@ def test_resource_view_context(self):
             resource
         )
         self.assertFalse(response.context["debug"])
-        self.assertEqual(
-            response.context["resource_thumbnail_base"],
-            "/staticfiles/img/resources/grid/thumbnails/"
-        )
         self.assertFalse(response.context["grouped_lessons"])
         self.assertEqual(
             response.context["thumbnail"],
             "static/images/thumbnail-grid"
         )
 
+    @override_settings(DJANGO_PRODUCTION=True)
+    def test_resource_view_resource_thumbnail_base_context_production_en(self):
+        resource = self.test_data.create_resource(
+            "grid",
+            "Grid",
+            "resources/grid.html",
+            "GridResourceGenerator",
+        )
+        kwargs = {
+            "resource_slug": resource.slug,
+        }
+        url = reverse("resources:resource", kwargs=kwargs)
+        response = self.client.get(url)
+        self.assertEqual(
+            response.context["resource_thumbnail_base"],
+            "/staticfiles/img/resources/grid/thumbnails/{}/".format(self.language)
+        )
+
+    @override_settings(DJANGO_PRODUCTION=True)
+    def test_resource_view_resource_thumbnail_base_context_production_de(self):
+        with translation.override("de"):
+            resource = self.test_data.create_resource(
+                "grid",
+                "Grid",
+                "resources/grid.html",
+                "GridResourceGenerator",
+            )
+            kwargs = {
+                "resource_slug": resource.slug,
+            }
+            url = reverse("resources:resource", kwargs=kwargs)
+            response = self.client.get(url)
+            self.assertEqual(
+                response.context["resource_thumbnail_base"],
+                "/staticfiles/img/resources/grid/thumbnails/de/"
+            )
+
+    @override_settings(DJANGO_PRODUCTION=True)
+    @override_settings(LANGUAGES=MULTIPLE_LANGUAGES_WITH_INCONTEXT)
+    def test_resource_view_resource_thumbnail_base_context_production_in_context(self):
+        resource = self.test_data.create_resource(
+            "grid",
+            "Grid",
+            "resources/grid.html",
+            "GridResourceGenerator",
+        )
+        kwargs = {
+            "resource_slug": resource.slug,
+        }
+        lang = settings.INCONTEXT_L10N_PSEUDOLANGUAGE
+        with translation.override(lang):
+            url = reverse("resources:resource", kwargs=kwargs)
+            response = self.client.get(url)
+            print(response.context["resource"])
+            self.assertEqual(
+                response.context["resource_thumbnail_base"],
+                "/staticfiles/img/resources/grid/thumbnails/en/"
+            )
+
     def test_resource_view_context_without_thumbnail(self):
         resource = self.test_data.create_resource(
             "grid",