Self hosted FLOSS fitness/workout, nutrition and weight tracker
Remove the deprecated exercise search endpoint
Roland Geiderffe173436d9e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1c20676e1..c0eac6bb1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -30,8 +30,10 @@ Automatically read the date from uploaded image to the gallery.and allows us to properly sync them to local instances as well.The API endpoint `/api/v2/variations/` API endpoint has been removed.-Improve serving size support for ingredients. Users can now log food ineveryday units like "1 Serving (2 biscuits)" or "1 Cup" instead of only grams,with serving sizes automatically imported from Open Food Facts.The `/api/v2/weightunit/` endpoint has been removed.++The deprecated API endpoint `/api/v2/exercise/search/` has been removed. Use the+regular `/api/v2/exerciseinfo/` endpoint with appropriate query parameters instead.diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.pyindex 76bbc626b..a28839cc5 100644--- a/wger/exercises/api/views.py+++ b/wger/exercises/api/views.py@@ -14,40 +14,21 @@# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.# Standard Library-import loggingfrom uuid import UUID# Djangofrom django.conf import settings-from django.contrib.postgres.search import TrigramSimilarity-from django.db.models import (- Prefetch,- Q,-)+from django.db.models import Prefetchfrom django.utils.decorators import method_decorator-from django.utils.translation import gettext as _from django.views.decorators.cache import cache_page# Third Partyfrom actstream import action as actstream_action-from drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import (- OpenApiParameter,- extend_schema,- inline_serializer,-)+from drf_spectacular.utils import extend_schemafrom easy_thumbnails.alias import aliases-from easy_thumbnails.exceptions import InvalidImageFormatErrorfrom easy_thumbnails.files import get_thumbnailerfrom rest_framework import viewsets-from rest_framework.decorators import (- action,- api_view,-)-from rest_framework.fields import (- CharField,- IntegerField,-)+from rest_framework.decorators import actionfrom rest_framework.generics import CreateAPIViewfrom rest_framework.response import Responsefrom rest_framework.viewsets import ModelViewSet@@ -82,15 +63,6 @@ from wger.exercises.models import (Translation,)from wger.exercises.views.helper import StreamVerbs-from wger.utils.constants import (- ENGLISH_SHORT_NAME,- SEARCH_ALL_LANGUAGES,-)-from wger.utils.db import is_postgres_db-from wger.utils.language import load_language---logger = logging.getLogger(__name__)class ExerciseViewSet(ModelViewSet):@@ -196,115 +168,6 @@ class ExerciseTranslationViewSet(ModelViewSet):)-@extend_schema(- parameters=[- OpenApiParameter(- 'term',- OpenApiTypes.STR,- OpenApiParameter.QUERY,- description='The name of the exercise to search',- required=True,- ),- OpenApiParameter(- 'language',- OpenApiTypes.STR,- OpenApiParameter.QUERY,- description='Comma separated list of language codes to search',- required=True,- ),- ],- # yapf: disable- responses={- 200: inline_serializer(- name='ExerciseSearchResponse',- fields={- 'value': CharField(),- 'data': inline_serializer(- name='ExerciseSearchItemResponse',- fields={- 'id': IntegerField(),- 'base_id': IntegerField(),- 'name': CharField(),- 'category': CharField(),- 'image': CharField(),- 'image_thumbnail': CharField(),- },- ),- },- )- },- # yapf: enable-)-@api_view(['GET'])-def search(request):- """- Searches for exercises.-- This format is currently used by the exercise search autocompleter- """- q = request.GET.get('term', None)- language_codes = request.GET.get('language', ENGLISH_SHORT_NAME)- response = {}- results = []-- if not q:- return Response(response)-- # Filter the appropriate languages- languages = [load_language(l) for l in language_codes.split(',')]- if language_codes == SEARCH_ALL_LANGUAGES:- query = Translation.objects.all()- else:- query = Translation.objects.filter(language__in=languages)-- query = query.only('name')-- # Postgres uses a full-text search- if is_postgres_db():- query = (- query.annotate(similarity=TrigramSimilarity('name', q))- .filter(Q(similarity__gt=0.15) | Q(alias__alias__icontains=q))- .order_by('-similarity', 'name')- )- else:- query = query.filter(Q(name__icontains=q) | Q(alias__alias__icontains=q))-- for translation in query:- image = None- thumbnail = None- if translation.main_image:- image_obj = translation.main_image- image = image_obj.image.url- t = get_thumbnailer(image_obj.image)- thumbnail = None- try:- thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).url- except InvalidImageFormatError as e:- logger.warning(- f'InvalidImageFormatError while processing thumbnails for '- f'image ID {image_obj.id}: {e}'- )- except OSError as e:- logger.warning(- f'OSError while processing thumbnails for image ID {image_obj.id}: {e}'- )-- result_json = {- 'value': translation.name,- 'data': {- 'id': translation.id,- 'base_id': translation.exercise_id,- 'name': translation.name,- 'category': _(translation.category.name),- 'image': image,- 'image_thumbnail': thumbnail,- },- }- results.append(result_json)- response['suggestions'] = results- return Response(response)--class ExerciseInfoViewset(viewsets.ReadOnlyModelViewSet):"""Read-only info API endpoint for exercise objects, grouped by the exercisediff --git a/wger/exercises/tests/api/test_search_api.py b/wger/exercises/tests/api/test_search_api.pyindex c8b4b773d..a4df6a4cf 100644--- a/wger/exercises/tests/api/test_search_api.py+++ b/wger/exercises/tests/api/test_search_api.py@@ -13,93 +13,102 @@# You should have received a copy of the GNU Affero General Public License# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.+# Standard Library+import json++# Django+from django.urls import reverse+# Third Partyfrom rest_framework import status# wger-from wger.core.tests.api_base_test import ApiBaseTestCase-from wger.core.tests.base_testcase import BaseTestCase+from wger.core.tests.base_testcase import WgerTestCase-class SearchExerciseApiTestCase(BaseTestCase, ApiBaseTestCase):- url = '/api/v2/exercise/search/'+class SearchExerciseApiTestCase(WgerTestCase):+ """+ Tests searching for exercises via the exerciseinfo endpoint's name__search filter+ """- def setUp(self):- super().setUp()- self.init_media_root()+ url = reverse('exerciseinfo-list')- def test_basic_search_logged_out(self):+ def search_exercise(self):"""- Logged-out users are also allowed to use the search+ Helper function to test basic searching for exercises"""- response = self.client.get(self.url + '?term=exercise')- result1 = response.data['suggestions'][0]+ # Search for "cool" should find exercise base containing "Very cool exercise"+ response = self.client.get(self.url, {'name__search': 'cool', 'format': 'json'})self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.data['suggestions']), 4)- self.assertEqual(result1['value'], 'An exercise')- self.assertEqual(result1['data']['id'], 1)+ result = json.loads(response.content.decode('utf8'))+ results = result['results']+ self.assertEqual(len(results), 1)+ self.assertEqual(results[0]['category']['name'], 'Another category')- def test_basic_search_logged_in(self):+ # Search for non-existent term should return no results+ response = self.client.get(self.url, {'name__search': 'Foobar', 'format': 'json'})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ result = json.loads(response.content.decode('utf8'))+ self.assertEqual(len(result['results']), 0)++ def test_search_logged_out(self):"""- Logged-in users get the same results+ Logged-out users are also allowed to use the search"""- self.authenticate('test')- response = self.client.get(self.url + '?term=exercise')- result1 = response.data['suggestions'][0]+ self.search_exercise()- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.data['suggestions']), 4)- self.assertEqual(result1['value'], 'An exercise')- self.assertEqual(result1['data']['id'], 1)+ def test_search_logged_in(self):+ """+ Logged-in users get the same results+ """+ self.user_login('test')+ self.search_exercise()def test_search_language_code_en(self):"""- Explicitly passing the en language code (same as no code)+ Explicitly passing the en language code"""- response = self.client.get(self.url + '?term=exercise&language=en')- result1 = response.data['suggestions'][0]-+ response = self.client.get(+ self.url,+ {'name__search': 'exercise', 'language__code': 'en', 'format': 'json'},+ )self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.data['suggestions']), 4)- self.assertEqual(result1['value'], 'An exercise')- self.assertEqual(result1['data']['id'], 1)+ result = json.loads(response.content.decode('utf8'))+ self.assertGreaterEqual(len(result['results']), 1)def test_search_language_code_en_no_results(self):"""The "Testübung" exercise should not be found when searching in English"""- response = self.client.get(self.url + '?term=Testübung&language=en')-+ response = self.client.get(+ self.url,+ {'name__search': 'Testübung', 'language__code': 'en', 'format': 'json'},+ )self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.data['suggestions']), 0)+ result = json.loads(response.content.decode('utf8'))+ self.assertEqual(len(result['results']), 0)def test_search_language_code_de(self):"""- The "Testübung" exercise should be only found when searching in German+ The "Testübung" exercise should be found when searching in German"""- response = self.client.get(self.url + '?term=Testübung&language=de')- result1 = response.data['suggestions'][0]-+ response = self.client.get(+ self.url,+ {'name__search': 'Testübung', 'language__code': 'de', 'format': 'json'},+ )self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.data['suggestions']), 1)- self.assertEqual(result1['value'], 'Weitere Testübung')- self.assertEqual(result1['data']['id'], 7)+ result = json.loads(response.content.decode('utf8'))+ self.assertEqual(len(result['results']), 1)def test_search_several_language_codes(self):"""Passing different language codes works correctly"""- response = self.client.get(self.url + '?term=demo&language=en,de')-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.data['suggestions']), 4)-- def test_search_all_languages(self):- """- Passing different language codes works correctly- """- response = self.client.get(self.url + '?term=demo&language=*')-+ response = self.client.get(+ self.url,+ {'name__search': 'demo', 'language__code': 'en,de', 'format': 'json'},+ )self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.data['suggestions']), 4)+ result = json.loads(response.content.decode('utf8'))+ self.assertGreaterEqual(len(result['results']), 1)diff --git a/wger/exercises/tests/test_exercise_translation.py b/wger/exercises/tests/test_exercise_translation.pyindex d80727b3c..a7a5c637a 100644--- a/wger/exercises/tests/test_exercise_translation.py+++ b/wger/exercises/tests/test_exercise_translation.py@@ -12,12 +12,6 @@## You should have received a copy of the GNU Affero General Public License-# Standard Library-import json--# Django-from django.urls import reverse-# Third Partyfrom rest_framework import status@@ -53,43 +47,6 @@ class ExercisesTestCase(WgerTestCase):Exercise test case"""- def search_exercise(self, fail=True):- """- Helper function to test searching for exercises- """-- # 1 hit, "Very cool exercise"- response = self.client.get(reverse('exercise-search'), {'term': 'cool'})- self.assertEqual(response.status_code, 200)- result = json.loads(response.content.decode('utf8'))- self.assertEqual(len(result), 1)- self.assertEqual(result['suggestions'][0]['value'], 'Very cool exercise')- self.assertEqual(result['suggestions'][0]['data']['id'], 2)- self.assertEqual(result['suggestions'][0]['data']['category'], 'Another category')- self.assertEqual(result['suggestions'][0]['data']['image'], None)- self.assertEqual(result['suggestions'][0]['data']['image_thumbnail'], None)-- # 0 hits, "Pending exercise"- response = self.client.get(reverse('exercise-search'), {'term': 'Foobar'})- self.assertEqual(response.status_code, 200)- result = json.loads(response.content.decode('utf8'))- self.assertEqual(len(result['suggestions']), 0)-- def test_search_exercise_anonymous(self):- """- Test deleting an exercise by an anonymous user- """-- self.search_exercise()-- def test_search_exercise_logged_in(self):- """- Test deleting an exercise by a logged-in user- """-- self.user_login('test')- self.search_exercise()-def test_exercise_records_historical_data(self):"""Test that changing exercise details generates a historical recorddiff --git a/wger/urls.py b/wger/urls.pyindex 7e837c394..415962da2 100644--- a/wger/urls.py+++ b/wger/urls.py@@ -294,7 +294,6 @@ urlpatterns += [path('i18n/', include('django.conf.urls.i18n')),path('robots.txt', TextTemplateView.as_view(template_name='robots.txt'), name='robots'),# API- path('api/v2/exercise/search/', exercises_api_views.search, name='exercise-search'),path('api/v2/exercise-submission/',exercises_api_views.ExerciseSubmissionViewSet.as_view(),diff --git a/wger/version.py b/wger/version.pyindex d18c873ec..6c4a74edc 100644--- a/wger/version.py+++ b/wger/version.py@@ -32,7 +32,7 @@ Minimum version of the mobile app required to access this server.Always use versions in the x.y.z format, without any suffixes like "beta1" or such."""-MIN_SERVER_VERSION = Version('2.4.0-alpha3')+MIN_SERVER_VERSION = Version('2.5.0')"""Minimum version of the server required to run sync commands on this server"""VERSION = Version('2.5.0')