Self hosted FLOSS fitness/workout, nutrition and weight tracker
Commit missing files
Roland Geiderf9cf709e97d4
diff --git a/wger/nutrition/management/commands/__init__.py b/wger/nutrition/management/commands/__init__.pynew file mode 100644index 000000000..1292caeab--- /dev/null+++ b/wger/nutrition/management/commands/__init__.py@@ -0,0 +1,15 @@+# This file is part of wger Workout Manager <https://github.com/wger-project>.+# Copyright (C) 2013 - 2021 wger Team+#+# 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 Affero General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <http://www.gnu.org/licenses/>.diff --git a/wger/nutrition/management/commands/download-ingredient-images.py b/wger/nutrition/management/commands/download-ingredient-images.pynew file mode 100644index 000000000..8f603d051--- /dev/null+++ b/wger/nutrition/management/commands/download-ingredient-images.py@@ -0,0 +1,121 @@+# -*- coding: utf-8 *-*++# 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+from django.core.exceptions import (+ ImproperlyConfigured,+ ValidationError,+)+from django.core.management.base import (+ BaseCommand,+ CommandError,+)+from django.core.validators import URLValidator++# Third Party+import requests+from requests.utils import default_user_agent++# wger+from wger import get_version+from wger.nutrition.models import (+ Image,+ Ingredient,+)+++IMAGE_API = "{0}/api/v2/ingredientimage/"+++class Command(BaseCommand):+ """+ Download ingredient images from wger.de and updates the local database++ Both the ingredients and the images are identified by their UUID, which can't+ be modified via the GUI.+ """++ help = (+ 'Download ingredient images from wger.de and update the local database\n'+ '\n'+ 'ATTENTION: The script will download the images from the server and add them\n'+ ' to your local ingredients. The ingredients are identified by\n'+ ' their UUID field, if you manually edited or changed it\n'+ ' the script will not be able to match them.'+ )++ def add_arguments(self, parser):+ parser.add_argument(+ '--remote-url',+ action='store',+ dest='remote_url',+ default='https://wger.de',+ help='Remote URL to fetch the exercises from (default: '+ 'https://wger.de)'+ )++ def handle(self, **options):++ if not settings.MEDIA_ROOT:+ raise ImproperlyConfigured('Please set MEDIA_ROOT in your settings file')++ remote_url = options['remote_url']+ try:+ val = URLValidator()+ val(remote_url)+ except ValidationError:+ raise CommandError('Please enter a valid URL')++ headers = {'User-agent': default_user_agent(f'wger/{get_version()} + requests')}++ # Get all images+ page = 1+ all_images_processed = False+ result = requests.get(IMAGE_API.format(remote_url), headers=headers).json()+ self.stdout.write('*** Processing images ***')+ while not all_images_processed:+ self.stdout.write('')+ self.stdout.write(f'*** Page {page}')+ self.stdout.write('')++ for image_data in result['results']:+ image_uuid = image_data['uuid']++ self.stdout.write(f'Processing image {image_uuid}')++ try:+ ingredient = Ingredient.objects.get(uuid=image_data['ingredient_uuid'])+ except Ingredient.DoesNotExist:+ self.stdout.write(' Remote ingredient not found in local DB, skipping...')+ continue++ try:+ Image.objects.get(uuid=image_uuid)+ self.stdout.write(' Image already present locally, skipping...')+ continue+ except Image.DoesNotExist:+ self.stdout.write(' Image not found in local DB, creating now...')+ retrieved_image = requests.get(image_data['image'], headers=headers)+ Image.from_json(ingredient, retrieved_image, image_data, headers)++ self.stdout.write(self.style.SUCCESS(' successfully saved'))++ if result['next']:+ page += 1+ result = requests.get(result['next'], headers=headers).json()+ else:+ all_images_processed = Truediff --git a/wger/nutrition/migrations/0009_auto_20210801_1350.py b/wger/nutrition/migrations/0009_auto_20210801_1350.pynew file mode 100644index 000000000..cd56fee9a--- /dev/null+++ b/wger/nutrition/migrations/0009_auto_20210801_1350.py@@ -0,0 +1,89 @@+# Generated by Django 3.2.3 on 2021-08-01 11:50++from django.db import migrations, models+import django.db.models.deletion+import uuid+import wger.nutrition.models.image+++def generate_uuids(apps, schema_editor):+ """+ Generate new UUIDs for each exercise+ :param apps:+ :param schema_editor:+ :return:+ """+ Ingredient = apps.get_model("nutrition", "Ingredient")+ for ingredient in Ingredient.objects.all():+ ingredient.uuid = uuid.uuid4()+ ingredient.save()+++class Migration(migrations.Migration):++ dependencies = [+ ('core', '0013_auto_20210726_1729'),+ ('nutrition', '0008_auto_20210102_1446'),+ ]++ operations = [+ migrations.AddField(+ model_name='ingredient',+ name='uuid',+ field=models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID'),+ ),+ migrations.CreateModel(+ name='Image',+ fields=[+ (+ 'id',+ models.AutoField(+ auto_created=True, primary_key=True, serialize=False, verbose_name='ID'+ )+ ),+ (+ 'license_author',+ models.CharField(+ blank=True,+ help_text=+ 'If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',+ max_length=50,+ null=True,+ verbose_name='Author'+ )+ ),+ ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')),+ (+ 'image',+ models.ImageField(+ help_text='Only PNG and JPEG formats are supported',+ upload_to=wger.nutrition.models.image.ingredient_image_upload_dir,+ verbose_name='Image'+ )+ ),+ ('last_update', models.DateTimeField(auto_now=True)),+ ('size', models.IntegerField()),+ ('source_url', models.URLField()),+ (+ 'license',+ models.ForeignKey(+ default=2,+ on_delete=django.db.models.deletion.CASCADE,+ to='core.license',+ verbose_name='License'+ )+ ),+ ],+ options={+ 'abstract': False,+ },+ ),+ migrations.AddField(+ model_name='ingredient',+ name='image',+ field=models.OneToOneField(+ null=True, on_delete=django.db.models.deletion.CASCADE, to='nutrition.image'+ ),+ ),+ migrations.RunPython(generate_uuids),+ ]diff --git a/wger/nutrition/models/image.py b/wger/nutrition/models/image.pynew file mode 100644index 000000000..60730861d--- /dev/null+++ b/wger/nutrition/models/image.py@@ -0,0 +1,86 @@+# This file is part of wger Workout Manager <https://github.com/wger-project>.+# Copyright (C) 2013 - 2021 wger Team+#+# 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 Affero General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <http://www.gnu.org/licenses/>.++# Standard Library+import pathlib+import uuid++# Django+from django.db import models+from django.utils.translation import gettext_lazy as _++# wger+from wger.core.models import License+from wger.utils.helpers import BaseImage+from wger.utils.models import AbstractLicenseModel+++def ingredient_image_upload_dir(instance, filename):+ """+ Returns the upload target for exercise images+ """+ ext = pathlib.Path(filename).suffix+ return "ingredients/{0}/{1}{2}".format(instance.ingredient.uuid, instance.uuid, ext)+++class Image(AbstractLicenseModel, models.Model, BaseImage):+ """+ Model for an ingredient image+ """++ uuid = models.UUIDField(+ default=uuid.uuid4,+ editable=False,+ verbose_name='UUID',+ )+ """Globally unique ID, to identify the image across installations"""++ image = models.ImageField(+ verbose_name=_('Image'),+ help_text=_('Only PNG and JPEG formats are supported'),+ upload_to=ingredient_image_upload_dir,+ )+ """Uploaded image"""++ last_update = models.DateTimeField(auto_now=True)+ """The date when this image was last synchronized """++ size = models.IntegerField()+ """The size of the image in bytes"""++ source_url = models.URLField()+ """The source of the image"""++ @classmethod+ def from_json(+ cls, connect_to, retrieved_image, json_data: dict, headers, generate_uuid: bool = False+ ):+ image: cls = super().from_json(+ connect_to, retrieved_image, json_data, headers, generate_uuid+ )++ image.ingredient = connect_to+ image.license = License.objects.get(pk=2)+ image.license_author = json_data['license_author']+ image.size = json_data['size']++ image.save_image(retrieved_image, json_data)++ image.save()++ connect_to.image = image+ connect_to.save()+ return image