From 30aa941b165cf29afd8933117064fffb0142dd04 Mon Sep 17 00:00:00 2001
From: ingo <ingo.leindecker@fro.at>
Date: Thu, 15 Feb 2018 12:38:51 +0100
Subject: [PATCH] Bug fixes

* Properly generate thumbnails for shows, hosts and notes
* Return thumbnails in API

See #22
---
 .gitignore             |  2 +-
 README.rst             | 11 +----------
 program/admin.py       |  2 +-
 program/models.py      | 10 +++++-----
 program/serializers.py | 40 +++++++++++++++++++++++++++++++++++++++-
 program/views.py       |  3 ++-
 6 files changed, 49 insertions(+), 19 deletions(-)

diff --git a/.gitignore b/.gitignore
index 451f1e67..ba273647 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,7 +7,7 @@ pv/site_media/buttons/s-*.png
 pv/site_media/buttons/r-*.png
 pv/site_media/show_images/*
 pv/site_media/note_images/*
-pv/site_media/user_images/*
+pv/site_media/host_images/*
 pv/site_media/__sized__/*
 pv/cache/*
 pv/mysql.cnf
\ No newline at end of file
diff --git a/README.rst b/README.rst
index 38be6f11..01039109 100644
--- a/README.rst
+++ b/README.rst
@@ -13,20 +13,17 @@ To get setup you must have the following installed:
  * virtualenv 1.11
 
 In Debian or Ubuntu (or derivatives) you should be able to achieve this with this command::
-
     $ sudo apt-get install libmysqlclient-dev libjpeg-dev python3.5-dev virtualenv
 
 Setting up the environment
 --------------------------
 
 Create a virtual environment where the dependencies will live::
-
     $ virtualenv -p python3.5 python
     $ source python/bin/activate
     (python)$
 
 Change into the base directory of this software and install the project dependencies::
-
     (python)$ pip3 install -r requirements.txt
 
 Setting up the database
@@ -35,23 +32,20 @@ Setting up the database
 By default the project is set up to run on a SQLite database.
 
 Create a file pv/local_settings.py and add at least the line::
-
     SECRET_KEY = 'secret key'
 
 (obviously replacing "secret key" with a key of your choice).
 
 Then run::
-
     (python)$ python manage.py migrate
     (python)$ python manage.py loaddata program/fixtures/*.yaml
 
 Setting up MySQL
 ----------------
 
-__Note:__ When adding your database, make sure you _don't_ use the collation _utf8mb4_unicode_ci_ or you will get a key length error during migration. (use e.g. _utf8_general_ci_ instead).
+**Note:** When adding your database, make sure you _don't_ use the collation _utf8mb4_unicode_ci_ or you will get a key length error during migration. (use e.g. _utf8_general_ci_ instead).
 
 To use MySQL, add the following to your local_settings.py (before migrating)::
-
     DATABASES = {
         'default': {
             'ENGINE': 'django.db.backends.mysql',
@@ -62,7 +56,6 @@ To use MySQL, add the following to your local_settings.py (before migrating)::
     }
 
 Create a file pv/mysql.cnf and give your MySQL credentials::
-
     [client]
     database =
     host = localhost
@@ -75,14 +68,12 @@ Adding an admin user
 --------------------
 
 In order to create an admin user (which you will need to login to the webinterface after the next step) run::
-
     (python)$ python manage.py createsuperuser
 
 Running a web server
 --------------------
 
 In development you should run::
-
     (python)$ python manage.py runserver
 
 
diff --git a/program/admin.py b/program/admin.py
index 3035001a..40de3e3a 100644
--- a/program/admin.py
+++ b/program/admin.py
@@ -400,7 +400,7 @@ class ShowAdmin(admin.ModelAdmin):
                 until = datetime.strptime(request.POST.get('ps_save_until'), '%Y-%m-%d').date()
                 is_repetition = request.POST.get('ps_save_is_repetition')
                 automation_id = int(request.POST.get('ps_save_automation_id')) if request.POST.get('ps_save_automation_id') != 'None' else 0
-                fallback_id = int(request.POST.get('fallback_id')) if request.POST.get('ps_save_fallback_id') != 'None' else 0
+                fallback_id = int(request.POST.get('ps_save_fallback_id')) if request.POST.get('ps_save_fallback_id') != 'None' else 0
 
                 # Put timeslot POST vars into lists with same indices
                 for i in range(num_inputs):
diff --git a/program/models.py b/program/models.py
index 0c7371d1..e85e733e 100644
--- a/program/models.py
+++ b/program/models.py
@@ -16,7 +16,7 @@ from dateutil.rrule import rrule
 
 from .utils import get_automation_id_choices
 
-from pv.settings import SECRET_KEY, AUTO_SET_UNTIL_DATE_TO_END_OF_YEAR, AUTO_SET_UNTIL_DATE_TO_DAYS_IN_FUTURE
+from pv.settings import THUMBNAIL_SIZES, AUTO_SET_UNTIL_DATE_TO_END_OF_YEAR, AUTO_SET_UNTIL_DATE_TO_DAYS_IN_FUTURE
 
 
 class Type(models.Model):
@@ -293,8 +293,8 @@ class Host(models.Model):
         super(Host, self).save(*args, **kwargs)
 
         # Generate thumbnails
-        if self.image.name and settings.THUMBNAIL_SIZES:
-            for size in settings.THUMBNAIL_SIZES:
+        if self.image.name and THUMBNAIL_SIZES:
+            for size in THUMBNAIL_SIZES:
                 thumbnail = self.image.crop[size].name
 
 
@@ -1224,6 +1224,6 @@ class Note(models.Model):
         super(Note, self).save(*args, **kwargs)
 
         # Generate thumbnails
-        if self.image.name and settings.THUMBNAIL_SIZES:
-            for size in settings.THUMBNAIL_SIZES:
+        if self.image.name and THUMBNAIL_SIZES:
+            for size in THUMBNAIL_SIZES:
                 thumbnail = self.image.crop[size].name
\ No newline at end of file
diff --git a/program/serializers.py b/program/serializers.py
index 53d87161..2787bd90 100644
--- a/program/serializers.py
+++ b/program/serializers.py
@@ -7,6 +7,8 @@ from profile.models import Profile
 from profile.serializers import ProfileSerializer
 from datetime import datetime
 
+from pv.settings import THUMBNAIL_SIZES
+
 class UserSerializer(serializers.ModelSerializer):
     # Add profile fields to JSON
     profile = ProfileSerializer()
@@ -89,6 +91,18 @@ class CategorySerializer(serializers.ModelSerializer):
 
 
 class HostSerializer(serializers.ModelSerializer):
+    thumbnails = serializers.SerializerMethodField() # Read-only
+
+    def get_thumbnails(self, host):
+        """Returns thumbnails"""
+        thumbnails = []
+
+        if host.image.name and THUMBNAIL_SIZES:
+            for size in THUMBNAIL_SIZES:
+                thumbnails.append(host.image.crop[size].name)
+
+        return thumbnails
+
     class Meta:
         model = Host
         fields = '__all__'
@@ -220,13 +234,25 @@ class ShowSerializer(serializers.HyperlinkedModelSerializer):
     musicfocus = serializers.PrimaryKeyRelatedField(queryset=MusicFocus.objects.all(),many=True)
     type = serializers.PrimaryKeyRelatedField(queryset=Type.objects.all())
     rtrcategory = serializers.PrimaryKeyRelatedField(queryset=RTRCategory.objects.all())
+    thumbnails = serializers.SerializerMethodField() # Read-only
+
+    def get_thumbnails(self, show):
+        """Returns thumbnails"""
+        thumbnails = []
+
+        if show.image.name and THUMBNAIL_SIZES:
+            for size in THUMBNAIL_SIZES:
+                thumbnails.append(show.image.crop[size].name)
+
+        return thumbnails
+
 
     class Meta:
         model = Show
         fields = ('id', 'name', 'slug', 'image', 'logo', 'short_description', 'description',
                   'email', 'website', 'created', 'last_updated', 'type', 'rtrcategory',
                   'predecessor_id', 'cba_series_id', 'fallback_id', 'category', 'hosts',
-                  'owners', 'language', 'topic', 'musicfocus')
+                  'owners', 'language', 'topic', 'musicfocus', 'thumbnails')
 
 
     def create(self, validated_data):
@@ -356,6 +382,18 @@ class NoteSerializer(serializers.ModelSerializer):
     show = serializers.PrimaryKeyRelatedField(queryset=Show.objects.all())
     timeslot = serializers.PrimaryKeyRelatedField(queryset=TimeSlot.objects.all())
     host = serializers.PrimaryKeyRelatedField(queryset=Host.objects.all())
+    thumbnails = serializers.SerializerMethodField() # Read-only
+
+    def get_thumbnails(self, note):
+        """Returns thumbnails"""
+        thumbnails = []
+
+        if note.image.name and THUMBNAIL_SIZES:
+            for size in THUMBNAIL_SIZES:
+                thumbnails.append(note.image.crop[size].name)
+
+        return thumbnails
+
 
     class Meta:
         model = Note
diff --git a/program/views.py b/program/views.py
index b191bfb7..e852edc7 100644
--- a/program/views.py
+++ b/program/views.py
@@ -433,7 +433,7 @@ class APIUserViewSet(viewsets.ModelViewSet):
 
 class APIShowViewSet(viewsets.ModelViewSet):
     """
-    /api/v1/shows/                                             Returns shows a user owns (GET, POST)
+    /api/v1/shows/                                             Returns all shows (GET, POST)
     /api/v1/shows/?active=true                                 Returns all active shows (GET)
     /api/v1/shows/?host=1                                      Returns shows assigned to a given host (GET)
     /api/v1/shows/?owner=1                                     Returns shows of a given owner (GET)
@@ -510,6 +510,7 @@ class APIShowViewSet(viewsets.ModelViewSet):
         """Returns a single show"""
         show = get_object_or_404(Show, pk=pk)
         serializer = ShowSerializer(show)
+
         return Response(serializer.data)
 
 
-- 
GitLab