Self hosted FLOSS fitness/workout, nutrition and weight tracker
Refactor some sync scripts
Roland Geider722d2b66a6ba
diff --git a/extras/scripts/create_ingredients_from_foodfacts.py b/extras/scripts/create_ingredients_from_foodfacts.pyindex 5113660b6..d32b01fe2 100644--- a/extras/scripts/create_ingredients_from_foodfacts.py+++ b/extras/scripts/create_ingredients_from_foodfacts.py@@ -28,20 +28,25 @@ from wger.nutrition.models import Ingredient # noqa: E402from wger.nutrition.models.sources import Sourcefrom wger.core.models import Language # noqa: E402-"""Simple script that imports and loads the Open Food Facts database into theingredients database.-NOTE: The file is VERY large (17 GB), so it takes a long time (> 3 hours) to+NOTE: The file is VERY large (40 GB), so it takes a long time (> 3 hours) toimport the data and create all the ingredients.* Requirements:-(note that the local mongo version needs to be compatible with the one used to+ (note that the local mongo version needs to be compatible with the one used tocreate the dump, otherwise the indices won't be compatible, it is best to usea newer version than the one found in the ubuntu/debian repos)+ - MongoDB+ https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/++ - Docker+ snap install docker+pip3 install pymongoapt-get install mongo-tools zip@@ -73,7 +78,6 @@ python3 filter-fixtures.pyzip ingredients.json.zip ingredients.json"""-client = MongoClient('mongodb://off:[email protected]', port=27017)db = client.admin@@ -87,9 +91,9 @@ class Mode(Enum):UPDATE = enum.auto()-MODE = Mode.INSERT+MODE = Mode.UPDATE-languages = {i[0]: Language.objects.get(short_name=i[0]) for i in settings.LANGUAGES}+languages = {l.short_name: l for l in Language.objects.all()}BULK_SIZE = 500bulk_update_bucket = []@@ -104,28 +108,35 @@ stats = {'new': 0,# Completeness status of ingredients as of 2021-11-18#-# Lang en has 5154 completed products out of 579495-# Lang de has 8882 completed products out of 90885-# Lang bg has 16 completed products out of 897-# Lang es has 6785 completed products out of 236210-# Lang ru has 481 completed products out of 8729-# Lang nl has 628 completed products out of 7428-# Lang pt has 482 completed products out of 5024-# Lang el has 27 completed products out of 544-# Lang cs has 154 completed products out of 1451-# Lang sv has 1234 completed products out of 3459-# Lang no has 9 completed products out of 155-# Lang fr has 45358 completed products out of 960096-# Lang it has 821 completed products out of 118270-# Lang pl has 2032 completed products out of 4978-# Lang uk has 4 completed products out of 158-# Lang tr has 8 completed products out of 425+# Lang az has 0 completed products out of 39+# Lang id has 6 completed products out of 845+# Lang cs has 78 completed products out of 3736+# Lang de has 972 completed products out of 157846+# Lang en has 959 completed products out of 905683+# Lang es has 533 completed products out of 300344+# Lang eo has 0 completed products out of 9+# Lang fr has 6677 completed products out of 1145075+# Lang hr has 56 completed products out of 1544+# Lang it has 809 completed products out of 211901+# Lang nl has 71 completed products out of 11202+# Lang no has 4 completed products out of 247+# Lang pl has 45 completed products out of 6793+# Lang pt has 132 completed products out of 9427+# Lang sv has 297 completed products out of 4501+# Lang tr has 3 completed products out of 1209+# Lang el has 6 completed products out of 880+# Lang bg has 31 completed products out of 3392+# Lang ru has 13 completed products out of 10799+# Lang uk has 1 completed products out of 297+# Lang he has 0 completed products out of 352+# Lang ar has 1 completed products out of 3426+# Lang fa has 0 completed products out of 577+# Lang zh has 2 completed products out of 913print('***********************************')print(languages.keys())print('***********************************')-for product in db.products.find({'lang': {"$in": list(languages.keys())}, 'complete': 1}):lang = product['lang']diff --git a/wger/__init__.py b/wger/__init__.pyindex c43be09c9..1a0c1d2f0 100644--- a/wger/__init__.py+++ b/wger/__init__.py@@ -7,6 +7,7 @@# Localfrom .celery_configuration import app+MIN_APP_VERSION = (1, 5, 0, 'final', 1)VERSION = (2, 2, 0, 'alpha', 2)diff --git a/wger/celery_configuration.py b/wger/celery_configuration.pyindex 20fd3502d..1564e05eb 100644--- a/wger/celery_configuration.py+++ b/wger/celery_configuration.py@@ -30,14 +30,3 @@ app.config_from_object('django.conf:settings', namespace='CELERY')# discover and load tasks.py from all registered Django appsapp.autodiscover_tasks()--# @app.on_after_finalize.connect-#def setup_periodic_tasks(sender, **kwargs):-# from wger.nutrition.tasks import test-# sender.add_periodic_task(30.0, test.s('world'), expires=10)--# Calls test('hello') every 10 seconds.-#sender.add_periodic_task(-# crontab(hour=7, minute=30, day_of_week=1),-# test.s('Happy Mondays!'),-#)diff --git a/wger/core/checks.py b/wger/core/checks.pyindex b00466445..000b37e5a 100644--- a/wger/core/checks.py+++ b/wger/core/checks.py@@ -31,7 +31,7 @@ def settings_check(app_configs, **kwargs):Error('Ingredient images configuration error',hint=f'Origin for ingredient images misconfigured. Valid options are '- f'{DOWNLOAD_INGREDIENT_OPTIONS}',+ f'{DOWNLOAD_INGREDIENT_OPTIONS}',obj=settings,id='wger.E001',)diff --git a/wger/exercises/management/commands/read-exercise-cleanup.py b/wger/exercises/management/commands/read-exercise-cleanup.pyindex 8e3294c3e..187d8ce13 100644--- a/wger/exercises/management/commands/read-exercise-cleanup.py+++ b/wger/exercises/management/commands/read-exercise-cleanup.py@@ -17,6 +17,7 @@# Standard Libraryimport csvimport pathlib+import re# Djangofrom django.core.files import File@@ -77,7 +78,7 @@ class Command(BaseCommand):def handle(self, **options):self.process_new_exercises(options)- self.delete_duplicates(options)+ # self.delete_duplicates(options)def process_new_exercises(self, options):csv_file = open('exercises_cleanup.csv', 'r', newline='')@@ -129,7 +130,9 @@ class Command(BaseCommand):# Update the base database.category = ExerciseCategory.objects.get(name=base_category)- base.save()++ if new_base:+ base.save()base_equipment_list = []if base_equipment:@@ -196,8 +199,7 @@ class Command(BaseCommand):continuenew_translation = exercise_uuid == UUID_NEW- if not options['create_on_new'] and new_translation:- self.stdout.write(f' Skipping creating new translation ...\n')+ if not new_translation:continuetranslation = Exercise.objects.get_or_create(@@ -228,10 +230,24 @@ class Command(BaseCommand):translation.license_author = exercise_authorif not translation.id:- message = f' New translation saved - {exercise_name}'+ message = f' New translation saved - {exercise_name} ({translation.uuid})'self.stdout.write(self.style.SUCCESS(message))- translation.save()+ if '(imported from Feeel)' in exercise_author:+ exercise_author = re.sub('\(imported from Feeel\)', '', exercise_author)+ for author in exercise_author.split(','):+ author = author.strip()+ author = f'{author} (imported from Feeel)'+ self.stdout.write(f' - Saving individual author {author}')+ if len(author) >= 60:+ self.stdout.write(+ self.style.WARNING(+ f' Author name is longer than 60 characters, skipping...'+ )+ )+ continue+ translation.license_author = author+ translation.save()# Set the aliases (replaces existing ones)if exercise_aliases:diff --git a/wger/exercises/management/commands/sync-exercises.py b/wger/exercises/management/commands/sync-exercises.pyindex ceb530eca..6d1672272 100644--- a/wger/exercises/management/commands/sync-exercises.py+++ b/wger/exercises/management/commands/sync-exercises.py@@ -21,38 +21,22 @@ from django.core.management.base import ()from django.core.validators import URLValidator-# Third Party-import requests-# wger-from wger.core.models import Language-from wger.exercises.models import (- DeletionLog,- Equipment,- Exercise,- ExerciseBase,- ExerciseCategory,- ExerciseImage,- ExerciseVideo,- Muscle,+from wger.exercises.sync import (+ delete_entries,+ sync_categories,+ sync_equipment,+ sync_exercises,+ sync_languages,+ sync_muscles,)-from wger.utils.requests import wger_headers---EXERCISE_API = "{0}/api/v2/exercisebaseinfo/?limit=100"-DELETION_LOG_API = "{0}/api/v2/deletion-log/?limit=100"-CATEGORY_API = "{0}/api/v2/exercisecategory/"-MUSCLE_API = "{0}/api/v2/muscle/"-LANGUAGE_API = "{0}/api/v2/language/"-EQUIPMENT_API = "{0}/api/v2/equipment/"class Command(BaseCommand):"""Synchronizes exercise data from a wger instance to the local database"""- remote_url = 'https://wger.de'- headers = {}+ remote_url = settings.WGER_SETTINGS['WGER_INSTANCE']help = """Synchronizes exercise data from a wger instance to the local database.This script also deletes entries that were removed on the server such@@ -95,215 +79,11 @@ class Command(BaseCommand):except ValidationError:raise CommandError('Please enter a valid URL')- self.headers = wger_headers()-# Process everything- self.sync_languages()- self.sync_categories()- self.sync_muscles()- self.sync_equipment()- self.sync_exercises()+ sync_languages(self.stdout.write, self.remote_url, self.style.SUCCESS)+ sync_categories(self.stdout.write, self.remote_url, self.style.SUCCESS)+ sync_muscles(self.stdout.write, self.remote_url, self.style.SUCCESS)+ sync_equipment(self.stdout.write, self.remote_url, self.style.SUCCESS)+ sync_exercises(self.stdout.write, self.remote_url, self.style.SUCCESS)if not options['skip_delete']:- self.delete_entries()-- def sync_exercises(self):- """Synchronize the exercises from the remote server"""-- self.stdout.write('*** Synchronizing exercises...')- page = 1- all_exercise_processed = False- result = requests.get(EXERCISE_API.format(self.remote_url), headers=self.headers).json()- while not all_exercise_processed:-- for data in result['results']:-- uuid = data['uuid']- license_id = data['license']['id']- category_id = data['category']['id']- license_author = data['license_author']- equipment = [Equipment.objects.get(pk=i['id']) for i in data['equipment']]- muscles = [Muscle.objects.get(pk=i['id']) for i in data['muscles']]- muscles_sec = [Muscle.objects.get(pk=i['id']) for i in data['muscles_secondary']]-- base, base_created = ExerciseBase.objects.get_or_create(- uuid=uuid,- defaults={'category_id': category_id},- )- self.stdout.write(f"{'created' if base_created else 'updated'} exercise {uuid}")-- base.muscles.set(muscles)- base.muscles_secondary.set(muscles_sec)- base.equipment.set(equipment)- base.save()-- for translation_data in data['exercises']:- trans_uuid = translation_data['uuid']- name = translation_data['name']- description = translation_data['description']- language_id = translation_data['language']-- translation, translation_created = Exercise.objects.get_or_create(- uuid=trans_uuid,- defaults={- 'language_id': language_id,- 'exercise_base': base- },- )- out = f"- {'created' if translation_created else 'updated'} translation " \- f"{translation.language.short_name} {trans_uuid} - {name}"- self.stdout.write(out)-- translation.name = name- translation.description = description- translation.language_id = language_id- translation.license_id = license_id- translation.license_author = license_author- translation.save()- self.stdout.write('')-- if result['next']:- page += 1- result = requests.get(result['next'], headers=self.headers).json()- else:- all_exercise_processed = True- self.stdout.write(self.style.SUCCESS('done!\n'))-- def delete_entries(self):- """Delete exercises that were removed on the server"""-- self.stdout.write('*** Deleting exercises data that was removed on the server...')-- page = 1- all_entries_processed = False- result = requests.get(DELETION_LOG_API.format(self.remote_url), headers=self.headers).json()- while not all_entries_processed:- for data in result['results']:- uuid = data['uuid']- model_type = data['model_type']-- if model_type == DeletionLog.MODEL_BASE:- try:- obj = ExerciseBase.objects.get(uuid=uuid)- obj.delete()- self.stdout.write(f'Deleted exercise base {uuid}')- except ExerciseBase.DoesNotExist:- pass-- elif model_type == DeletionLog.MODEL_TRANSLATION:- try:- obj = Exercise.objects.get(uuid=uuid)- obj.delete()- self.stdout.write(f"Deleted translation {uuid} ({data['comment']})")- except Exercise.DoesNotExist:- pass-- elif model_type == DeletionLog.MODEL_IMAGE:- try:- obj = ExerciseImage.objects.get(uuid=uuid)- obj.delete()- self.stdout.write(f'Deleted image {uuid}')- except ExerciseImage.DoesNotExist:- pass-- elif model_type == DeletionLog.MODEL_VIDEO:- try:- obj = ExerciseVideo.objects.get(uuid=uuid)- obj.delete()- self.stdout.write(f'Deleted video {uuid}')- except ExerciseVideo.DoesNotExist:- pass-- if result['next']:- page += 1- result = requests.get(result['next'], headers=self.headers).json()- else:- all_entries_processed = True- self.stdout.write(self.style.SUCCESS('done!\n'))-- def sync_equipment(self):- """Synchronize the equipment from the remote server"""-- self.stdout.write('*** Synchronizing equipment...')- result = requests.get(EQUIPMENT_API.format(self.remote_url), headers=self.headers).json()- for data in result['results']:- equipment_id = data['id']- equipment_name = data['name']-- equipment, created = Equipment.objects.get_or_create(- pk=equipment_id,- defaults={'name': equipment_name},- )-- if created:- self.stdout.write(f'Saved new equipment {equipment_name}')-- self.stdout.write(self.style.SUCCESS('done!\n'))-- def sync_muscles(self):- """Synchronize the muscles from the remote server"""-- self.stdout.write('*** Synchronizing muscles...')- result = requests.get(MUSCLE_API.format(self.remote_url), headers=self.headers).json()- for data in result['results']:- muscle_id = data['id']- muscle_name = data['name']- muscle_is_front = data['is_front']- muscle_name_en = data['name_en']- muscle_url_main = data['image_url_main']- muscle_url_secondary = data['image_url_secondary']-- muscle, created = Muscle.objects.get_or_create(- pk=muscle_id,- defaults={- 'name': muscle_name,- 'name_en': muscle_name_en,- 'is_front': muscle_is_front,- },- )-- if created:- self.stdout.write(- f'Saved new muscle {muscle_name}. Save the corresponding images manually:'- )- self.stdout.write(f' - {self.remote_url}{muscle_url_main}')- self.stdout.write(f' - {self.remote_url}{muscle_url_secondary}')-- self.stdout.write(self.style.SUCCESS('done!\n'))-- def sync_categories(self):- """Synchronize the categories from the remote server"""-- self.stdout.write('*** Synchronizing categories...')- result = requests.get(CATEGORY_API.format(self.remote_url), headers=self.headers).json()- for data in result['results']:- category_id = data['id']- category_name = data['name']-- category, created = ExerciseCategory.objects.get_or_create(- pk=category_id,- defaults={'name': category_name},- )-- if created:- self.stdout.write(f'Saved new category {category_name}')-- self.stdout.write(self.style.SUCCESS('done!\n'))-- def sync_languages(self):- """Synchronize the languages from the remote server"""-- self.stdout.write('*** Synchronizing languages...')- result = requests.get(LANGUAGE_API.format(self.remote_url), headers=self.headers).json()- for data in result['results']:- short_name = data['short_name']- full_name = data['full_name']-- language, created = Language.objects.get_or_create(- short_name=short_name,- defaults={'full_name': full_name},- )-- if created:- self.stdout.write(f'Saved new language {full_name}')-- self.stdout.write(self.style.SUCCESS('done!\n'))+ delete_entries(self.stdout.write, self.remote_url, self.style.SUCCESS)diff --git a/wger/exercises/sync.py b/wger/exercises/sync.pynew file mode 100644index 000000000..7eaa391a0--- /dev/null+++ b/wger/exercises/sync.py@@ -0,0 +1,281 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++# Django+from django.conf import settings++# Third Party+import requests++# wger+from wger.core.models import Language+from wger.exercises.models import (+ DeletionLog,+ Equipment,+ Exercise,+ ExerciseBase,+ ExerciseCategory,+ ExerciseImage,+ ExerciseVideo,+ Muscle,+)+from wger.utils.requests import wger_headers+++EXERCISE_API = "{0}/api/v2/exercisebaseinfo/?limit=100"+DELETION_LOG_API = "{0}/api/v2/deletion-log/?limit=100"+CATEGORY_API = "{0}/api/v2/exercisecategory/"+MUSCLE_API = "{0}/api/v2/muscle/"+LANGUAGE_API = "{0}/api/v2/language/"+EQUIPMENT_API = "{0}/api/v2/equipment/"+++def sync_exercises(+ print_fn,+ remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],+ style_fn=lambda x: x,+):+ """Synchronize the exercises from the remote server"""+ headers = wger_headers()++ print_fn('*** Synchronizing exercises...')+ page = 1+ all_exercise_processed = False+ result = requests.get(EXERCISE_API.format(remote_url), headers=headers).json()+ while not all_exercise_processed:++ for data in result['results']:++ uuid = data['uuid']+ license_id = data['license']['id']+ category_id = data['category']['id']+ license_author = data['license_author']+ equipment = [Equipment.objects.get(pk=i['id']) for i in data['equipment']]+ muscles = [Muscle.objects.get(pk=i['id']) for i in data['muscles']]+ muscles_sec = [Muscle.objects.get(pk=i['id']) for i in data['muscles_secondary']]++ base, base_created = ExerciseBase.objects.get_or_create(+ uuid=uuid,+ defaults={'category_id': category_id},+ )+ print_fn(f"{'created' if base_created else 'updated'} exercise {uuid}")++ base.muscles.set(muscles)+ base.muscles_secondary.set(muscles_sec)+ base.equipment.set(equipment)+ base.save()++ for translation_data in data['exercises']:+ trans_uuid = translation_data['uuid']+ name = translation_data['name']+ description = translation_data['description']+ language_id = translation_data['language']++ translation, translation_created = Exercise.objects.get_or_create(+ uuid=trans_uuid,+ defaults={+ 'language_id': language_id,+ 'exercise_base': base+ },+ )+ out = f"- {'created' if translation_created else 'updated'} translation " \+ f"{translation.language.short_name} {trans_uuid} - {name}"+ print_fn(out)++ translation.name = name+ translation.description = description+ translation.language_id = language_id+ translation.license_id = license_id+ translation.license_author = license_author+ translation.save()+ print_fn('')++ if result['next']:+ page += 1+ result = requests.get(result['next'], headers=headers).json()+ else:+ all_exercise_processed = True+ print_fn(style_fn('done!\n'))+++def sync_languages(+ print_fn,+ remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],+ style_fn=lambda x: x,+):+ """Synchronize the languages from the remote server"""+ headers = wger_headers()++ print_fn('*** Synchronizing languages...')+ result = requests.get(LANGUAGE_API.format(remote_url), headers=headers).json()+ for data in result['results']:+ short_name = data['short_name']+ full_name = data['full_name']++ language, created = Language.objects.get_or_create(+ short_name=short_name,+ defaults={'full_name': full_name},+ )++ if created:+ print_fn(f'Saved new language {full_name}')++ print_fn(style_fn('done!\n'))+++def sync_categories(+ print_fn,+ remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],+ style_fn=lambda x: x,+):+ """Synchronize the categories from the remote server"""++ headers = wger_headers()++ print_fn('*** Synchronizing categories...')+ result = requests.get(CATEGORY_API.format(remote_url), headers=headers).json()+ for data in result['results']:+ category_id = data['id']+ category_name = data['name']++ category, created = ExerciseCategory.objects.get_or_create(+ pk=category_id,+ defaults={'name': category_name},+ )++ if created:+ print_fn(f'Saved new category {category_name}')++ print_fn(style_fn('done!\n'))+++def sync_muscles(+ print_fn,+ remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],+ style_fn=lambda x: x,+):+ """Synchronize the muscles from the remote server"""++ headers = wger_headers()++ print_fn('*** Synchronizing muscles...')+ result = requests.get(MUSCLE_API.format(remote_url), headers=headers).json()+ for data in result['results']:+ muscle_id = data['id']+ muscle_name = data['name']+ muscle_is_front = data['is_front']+ muscle_name_en = data['name_en']+ muscle_url_main = data['image_url_main']+ muscle_url_secondary = data['image_url_secondary']++ muscle, created = Muscle.objects.get_or_create(+ pk=muscle_id,+ defaults={+ 'name': muscle_name,+ 'name_en': muscle_name_en,+ 'is_front': muscle_is_front,+ },+ )++ if created:+ print_fn(f'Saved new muscle {muscle_name}. Save the corresponding images manually:')+ print_fn(f' - {remote_url}{muscle_url_main}')+ print_fn(f' - {remote_url}{muscle_url_secondary}')++ print_fn(style_fn('done!\n'))+++def sync_equipment(+ print_fn,+ remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],+ style_fn=lambda x: x,+):+ """Synchronize the equipment from the remote server"""++ headers = wger_headers()++ print_fn('*** Synchronizing equipment...')+ result = requests.get(EQUIPMENT_API.format(remote_url), headers=headers).json()+ for data in result['results']:+ equipment_id = data['id']+ equipment_name = data['name']++ equipment, created = Equipment.objects.get_or_create(+ pk=equipment_id,+ defaults={'name': equipment_name},+ )++ if created:+ print_fn(f'Saved new equipment {equipment_name}')++ print_fn(style_fn('done!\n'))+++def delete_entries(+ print_fn,+ remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],+ style_fn=lambda x: x,+):+ """Delete exercises that were removed on the server"""++ headers = wger_headers()++ print_fn('*** Deleting exercises data that was removed on the server...')++ page = 1+ all_entries_processed = False+ result = requests.get(DELETION_LOG_API.format(remote_url), headers=headers).json()+ while not all_entries_processed:+ for data in result['results']:+ uuid = data['uuid']+ model_type = data['model_type']++ if model_type == DeletionLog.MODEL_BASE:+ try:+ obj = ExerciseBase.objects.get(uuid=uuid)+ obj.delete()+ print_fn(f'Deleted exercise base {uuid}')+ except ExerciseBase.DoesNotExist:+ pass++ elif model_type == DeletionLog.MODEL_TRANSLATION:+ try:+ obj = Exercise.objects.get(uuid=uuid)+ obj.delete()+ print_fn(f"Deleted translation {uuid} ({data['comment']})")+ except Exercise.DoesNotExist:+ pass++ elif model_type == DeletionLog.MODEL_IMAGE:+ try:+ obj = ExerciseImage.objects.get(uuid=uuid)+ obj.delete()+ print_fn(f'Deleted image {uuid}')+ except ExerciseImage.DoesNotExist:+ pass++ elif model_type == DeletionLog.MODEL_VIDEO:+ try:+ obj = ExerciseVideo.objects.get(uuid=uuid)+ obj.delete()+ print_fn(f'Deleted video {uuid}')+ except ExerciseVideo.DoesNotExist:+ pass++ if result['next']:+ page += 1+ result = requests.get(result['next'], headers=headers).json()+ else:+ all_entries_processed = True+ print_fn(style_fn('done!\n'))diff --git a/wger/exercises/tasks.py b/wger/exercises/tasks.pynew file mode 100644index 000000000..5e12d5e7e--- /dev/null+++ b/wger/exercises/tasks.py@@ -0,0 +1,56 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++# Standard Library+import logging++# Third Party+from celery.schedules import crontab++# wger+from wger.celery_configuration import app+from wger.exercises.sync import (+ delete_entries,+ sync_categories,+ sync_equipment,+ sync_exercises,+ sync_languages,+ sync_muscles,+)+++logger = logging.getLogger(__name__)+++def sync_exercises_task():+ """+ Fetches the current exercises from the default wger instance+ """+ sync_languages(logger.info)+ sync_categories(logger.info)+ sync_muscles(logger.info)+ sync_equipment(logger.info)+ sync_exercises(logger.info)+ sync_exercises(logger.info)+ delete_entries(logger.info)++[email protected]_after_finalize.connect+def setup_periodic_tasks(sender, **kwargs):+ sender.add_periodic_task(+ crontab(hour=10, minute=30, day_of_week='monday'),+ sync_exercises_task.s(),+ name='Regularly sync exercises',+ )diff --git a/wger/nutrition/models/ingredient.py b/wger/nutrition/models/ingredient.pyindex 15576449b..1f14c860e 100644--- a/wger/nutrition/models/ingredient.py+++ b/wger/nutrition/models/ingredient.py@@ -41,7 +41,6 @@ from django.utils.translation import gettext_lazy as _# wgerfrom wger.core.models import Language-from wger.nutrition.tasks import fetch_ingredient_image_taskfrom wger.utils.cache import cache_mapperfrom wger.utils.constants import TWOPLACESfrom wger.utils.managers import SubmissionManager@@ -453,4 +452,6 @@ class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):return# Let celery fetch the image+ # wger+ from wger.nutrition.tasks import fetch_ingredient_image_taskfetch_ingredient_image_task.delay(self.pk)diff --git a/wger/nutrition/sync.py b/wger/nutrition/sync.pynew file mode 100644index 000000000..7d63e7be6--- /dev/null+++ b/wger/nutrition/sync.py@@ -0,0 +1,125 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++# Standard Library+import logging+import os+from typing import Optional++# Django+from django.conf import settings+from django.db import IntegrityError++# Third Party+import requests++# wger+from wger.nutrition.models import (+ Image,+ Source,+)+from wger.utils.constants import (+ DOWNLOAD_INGREDIENT_OFF,+ DOWNLOAD_INGREDIENT_WGER,+)+from wger.utils.requests import wger_headers+++logger = logging.getLogger(__name__)+++def fetch_ingredient_image(pk: int):+ # wger+ from wger.nutrition.models import Ingredient++ ingredient = Ingredient.objects.get(pk=pk)+ logger.info(f'Fetching image for ingredient {pk}')++ if hasattr(ingredient, 'image'):+ return++ if ingredient.source_name != Source.OPEN_FOOD_FACTS.value:+ return++ if not ingredient.source_url:+ return++ if settings.TESTING:+ return++ if settings.WGER_SETTINGS['DOWNLOAD_INGREDIENT_IMAGES'] == DOWNLOAD_INGREDIENT_OFF:+ fetch_image_from_off(ingredient)+ elif settings.WGER_SETTINGS['DOWNLOAD_INGREDIENT_IMAGES'] == DOWNLOAD_INGREDIENT_WGER:+ fetch_image_from_wger_instance(ingredient)+++def fetch_image_from_wger_instance(ingredient):+ url = f"{settings.WGER_SETTINGS['WGER_INSTANCE']}/api/v2/ingredient-image/{ingredient.pk}"+ result = requests.get(url, headers=wger_headers()).json()+ image_uuid = result['uuid']+ try:+ Image.objects.get(uuid=image_uuid)+ logger.info('image already present locally, skipping...')+ return+ except Image.DoesNotExist:+ retrieved_image = requests.get(result['image'], headers=wger_headers())+ Image.from_json(ingredient, retrieved_image, result)+++def fetch_image_from_off(ingredient):+ # Everything looks fine, go ahead+ logger.info(f'Trying to fetch image from OFF for {ingredient.name} (UUID: {ingredient.uuid})')+ headers = wger_headers()++ # Fetch the product data+ product_data = requests.get(ingredient.source_url, headers=headers).json()+ image_url: Optional[str] = product_data['product'].get('image_front_url')+ if not image_url:+ logger.info('Product data has no "image_front_url" key')+ return+ image_data = product_data['product']['images']++ # Download the image file+ response = requests.get(image_url, headers=headers)+ if response.status_code != 200:+ logger.info(f'An error occurred! Status code: {response.status_code}')+ return++ # Parse the file name, looks something like this:+ # https://images.openfoodfacts.org/images/products/00975957/front_en.5.400.jpg+ image_name: str = image_url.rpartition("/")[2].partition(".")[0]++ # Retrieve the uploader name+ try:+ image_id: str = image_data[image_name]['imgid']+ uploader_name: str = image_data[image_id]['uploader']+ except KeyError as e:+ logger.info('could not load all image information, skipping...', e)+ return++ # Save to DB+ image_data = {+ 'image': os.path.basename(image_url),+ 'license_author': uploader_name,+ 'size': len(response.content)+ }+ try:+ Image.from_json(ingredient, response, image_data, generate_uuid=True)+ # Due to a race condition (e.g. when adding tasks over the search), we might+ # try to save an image to an ingredient that already has one. In that case,+ # just ignore the error+ except IntegrityError:+ logger.info('Ingredient has already an image, skipping...')+ return+ logger.info('Image successfully saved')diff --git a/wger/nutrition/tasks.py b/wger/nutrition/tasks.pyindex cc7491a49..618a9051b 100644--- a/wger/nutrition/tasks.py+++ b/wger/nutrition/tasks.py@@ -12,33 +12,12 @@## You should have received a copy of the GNU Affero General Public License-# Standard Library-import logging-import os-from typing import Optional--# Django-from django.conf import settings-from django.db import IntegrityError--# Third Party-import requests-from celery import shared_task-# wger-from wger.nutrition.models import Image-from wger.nutrition.models.sources import Source-from wger.utils.constants import (- DOWNLOAD_INGREDIENT_OFF,- DOWNLOAD_INGREDIENT_WGER,-)-from wger.utils.requests import wger_headers+from wger.celery_configuration import app+from wger.nutrition.sync import fetch_ingredient_image-logger = logging.getLogger(__name__)---@shared_task()def fetch_ingredient_image_task(pk: int):"""Fetches the ingredient image from Open Food Facts servers if it is not available locally@@ -46,90 +25,3 @@ def fetch_ingredient_image_task(pk: int):Returns the image if it is already present in the DB"""fetch_ingredient_image(pk)---def fetch_ingredient_image(pk: int):- # wger- from wger.nutrition.models import Ingredient-- ingredient = Ingredient.objects.get(pk=pk)- logger.info(f'Fetching image for ingredient {pk}')-- if hasattr(ingredient, 'image'):- return-- if ingredient.source_name != Source.OPEN_FOOD_FACTS.value:- return-- if not ingredient.source_url:- return-- if settings.TESTING:- return-- if settings.WGER_SETTINGS['DOWNLOAD_INGREDIENT_IMAGES'] == DOWNLOAD_INGREDIENT_OFF:- fetch_image_from_off(ingredient)- elif settings.WGER_SETTINGS['DOWNLOAD_INGREDIENT_IMAGES'] == DOWNLOAD_INGREDIENT_WGER:- fetch_image_from_wger_instance(ingredient)---def fetch_image_from_wger_instance(ingredient):- url = f"{settings.WGER_SETTINGS['WGER_INSTANCE']}/api/v2/ingredient-image/{ingredient.pk}"- result = requests.get(url, headers=wger_headers()).json()- image_uuid = result['uuid']- try:- Image.objects.get(uuid=image_uuid)- logger.info('image already present locally, skipping...')- return- except Image.DoesNotExist:- retrieved_image = requests.get(result['image'], headers=wger_headers())- Image.from_json(ingredient, retrieved_image, result)---def fetch_image_from_off(ingredient):-- # Everything looks fine, go ahead- logger.info(f'Trying to fetch image from OFF for {ingredient.name} (UUID: {ingredient.uuid})')- headers = wger_headers()-- # Fetch the product data- product_data = requests.get(ingredient.source_url, headers=headers).json()- image_url: Optional[str] = product_data['product'].get('image_front_url')- if not image_url:- logger.info('Product data has no "image_front_url" key')- return- image_data = product_data['product']['images']-- # Download the image file- response = requests.get(image_url, headers=headers)- if response.status_code != 200:- logger.info(f'An error occurred! Status code: {response.status_code}')- return-- # Parse the file name, looks something like this:- # https://images.openfoodfacts.org/images/products/00975957/front_en.5.400.jpg- image_name: str = image_url.rpartition("/")[2].partition(".")[0]-- # Retrieve the uploader name- try:- image_id: str = image_data[image_name]['imgid']- uploader_name: str = image_data[image_id]['uploader']- except KeyError as e:- logger.info('could not load all image information, skipping...', e)- return-- # Save to DB- image_data = {- 'image': os.path.basename(image_url),- 'license_author': uploader_name,- 'size': len(response.content)- }- try:- Image.from_json(ingredient, response, image_data, generate_uuid=True)- # Due to a race condition (e.g. when adding tasks over the search), we might- # try to save an image to an ingredient that already has one. In that case,- # just ignore the error- except IntegrityError:- logger.info('Ingredient has already an image, skipping...')- return- logger.info('Image successfully saved')diff --git a/wger/nutrition/tests/test_tasks.py b/wger/nutrition/tests/test_tasks.pyindex 3151ba22e..90c91e30a 100644--- a/wger/nutrition/tests/test_tasks.py+++ b/wger/nutrition/tests/test_tasks.py@@ -23,7 +23,7 @@ from unittest.mock import (# wgerfrom wger.core.tests.base_testcase import WgerTestCasefrom wger.nutrition.models import Ingredient-from wger.nutrition.tasks import (+from wger.nutrition.sync import (fetch_ingredient_image,logger,)@@ -45,7 +45,7 @@ class MockOffResponse:return {"product": {'image_front_url':- 'https://images.openfoodfacts.org/images/products/00975957/front_en.5.400.jpg',+ 'https://images.openfoodfacts.org/images/products/00975957/front_en.5.400.jpg','images': {'front_en': {'imgid': '12345',@@ -69,7 +69,7 @@ class MockWgerApiResponse:return {"product": {'image_front_url':- 'https://images.openfoodfacts.org/images/products/00975957/front_en.5.400.jpg',+ 'https://images.openfoodfacts.org/images/products/00975957/front_en.5.400.jpg','images': {'front_en': {'imgid': '12345',@@ -122,8 +122,7 @@ class FetchIngredientImageTestCase(WgerTestCase):"""with self.settings(- WGER_SETTINGS={'DOWNLOAD_INGREDIENT_IMAGES': DOWNLOAD_INGREDIENT_OFF},- TESTING=False+ WGER_SETTINGS={'DOWNLOAD_INGREDIENT_IMAGES': DOWNLOAD_INGREDIENT_OFF}, TESTING=False):result = fetch_ingredient_image(1)diff --git a/wger/settings_global.py b/wger/settings_global.pyindex 453005c39..6372d9028 100644--- a/wger/settings_global.py+++ b/wger/settings_global.py@@ -24,6 +24,7 @@ from datetime import timedelta# wgerfrom wger.utils.constants import DOWNLOAD_INGREDIENT_WGER+"""This file contains the global settings that don't usually need to be changed.For a full list of options, visit:diff --git a/wger/tasks.py b/wger/tasks.pyindex fff018613..76ded9788 100644--- a/wger/tasks.py+++ b/wger/tasks.py@@ -45,8 +45,7 @@ FIXTURE_URL = 'https://github.com/wger-project/data/raw/master/fixtures/''port':'Port to use. Default: 8000','settings-path':- 'Path to settings file (absolute path). Leave empty for '- 'default',+ 'Path to settings file (absolute path). Leave empty for default','extra-args':'Additional arguments to pass to the builtin server. Pass as string: ''"--arg1 --arg2=value". Default: none'