Self hosted FLOSS fitness/workout, nutrition and weight tracker
Merge master
Roland Geidere8fe9e7649c5
diff --cc AUTHORS.rstindex f3cf97107,e0a6c34c9..1aedf3041--- a/AUTHORS.rst+++ b/AUTHORS.rst@@@ -56,8 -56,7 +56,9 @@@ Developer* Sidrah Madiha Siddiqui https://github.com/Sidrah-Madiha* Calvin Walden - https://github.com/calvinrw* Jack Mulligan - https://github.com/jackmulligan-ire+ * Kristopher Newsome - https://github.com/sysadmin75+* Emma Muth - https://github.com/emmaamuth+* Sophia Reed - https://github.com/sophialrTranslators-----------diff --cc extras/docker/apache/Dockerfileindex ad7dbbea2,6b06a6341..0dde1e61f--- a/extras/docker/apache/Dockerfile+++ b/extras/docker/apache/Dockerfile@@@ -49,6 -50,6 +50,7 @@@ RUN apt-get updateapache2 \cron \libapache2-mod-wsgi-py3 \++ python3-wheel \&& rm -rf /var/lib/apt/lists/*# Configure apache@@@ -81,7 -82,7 +83,6 @@@ WORKDIR /home/wger/srRUN python3 -m venv /home/wger/venvRUN . /home/wger/venv/bin/activate \&& pip install --upgrade pip \-- && pip install wheel \&& pip install --no-cache /wheels/* \&& python setup.py develop \&& wger create-settings --database-path /home/wger/db/database.sqlite \diff --cc package.jsonindex dbd9e467c,ddd8e3704..cad66e0dc--- a/package.json+++ b/package.json@@@ -16,22 -16,22 +16,23 @@@},"homepage": "https://github.com/wger-project/wger","dependencies": {- "yarn": "^1.22.5","Sortable": "RubaXa/Sortable#1.13.0",- "bootstrap": "twbs/bootstrap#4.x",- "components-font-awesome": "components/font-awesome#5.15.3",- "d3": "mbostock-bower/d3-bower#>=5",- "datatables": "DataTables/DataTables#1.10.x",+ "bootstrap": "4.6.0",+ "components-font-awesome": "5.9.0",+ "d3": "^7.0.0",+ "datatables": "^1.10.18","devbridge-autocomplete": "^1.4.11","jquery": "^3.6.0",- "metrics-graphics": "mozilla/metrics-graphics#2.15.x",+ "masonry-layout": "^4.2.2",+ "metrics-graphics": "^2.15.6",+ "popper.js": "^1.16.1","shariff": "^3.2.1",- "tinymce": "^5.8.1",- "masonry-layout": "^4.2.2"+ "tinymce": "^5.8.2",+ "yarn": "^1.22.5"},"scripts": {- "build:css:sass": "sass wger/core/static/scss/main.scss:wger/core/static/yarn/bootstrap-compiled.css"+ "build:css:sass": "sass wger/core/static/scss/main.scss:wger/core/static/yarn/bootstrap-compiled.css",+ "build:angular": "cd angular && ng build --configuration production --output-path ../wger/core/static/angular --output-hashing none"},"engines": {"yarn": ">= 1.0.0"diff --cc requirements.txtindex 0cbf24cd6,d48fa50bc..c47579c98--- a/requirements.txt+++ b/requirements.txt@@@ -8,9 -8,7 +8,9 @@@ django-bootstrap-breadcrumbs~=0.django-formtools~=2.3django-recaptcha~=2.0.6Django~=3.2- django-crispy-forms~=1.11+ django-crispy-forms~=1.12+django-simple-history~=3.0+django-email-verification~=0.1.0django_compressor~=2.4django_extensions~=3.1django-storages~=1.11diff --cc wger/core/forms.pyindex 602ba4c9a,95c9ffc3d..e534717ba--- a/wger/core/forms.py+++ b/wger/core/forms.py@@@ -34,15 -34,17 +34,19 @@@ from django.utils.translation import ge# Third Partyfrom captcha.fields import ReCaptchaFieldfrom captcha.widgets import ReCaptchaV3+ from crispy_forms.bootstrap import (+ Accordion,+ AccordionGroup,+ )from crispy_forms.helper import FormHelperfrom crispy_forms.layout import (+ HTML,ButtonHolder,Column,+ Fieldset,Layout,Row,- Submit,+ Submit)# wgerdiff --cc wger/core/models/profile.pyindex 000000000,407581f16..eac4a74b0mode 000000,100644..100644--- a/wger/core/models/profile.py+++ b/wger/core/models/profile.py@@@ -1,0 -1,537 +1,543 @@@+ # 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 datetime+ import decimal++ # Django+ from django.contrib.auth.models import User+ from django.core.exceptions import ValidationError+ from django.core.validators import (+ MaxValueValidator,+ MinValueValidator,+ )+ from django.db import models+ from django.db.models import IntegerField+ from django.utils.translation import gettext_lazy as _++ # wger+ from wger.gym.models import Gym+ from wger.utils.constants import TWOPLACES+ from wger.utils.units import AbstractWeight+ from wger.weight.models import WeightEntry++ # Local+ from .language import Language+++ def birthdate_validator(birthdate):+ """+ Checks to see if entered birthdate (datetime.date object) is+ between 10 and 100 years of age.+ """+ max_year = birthdate.replace(year=(birthdate.year + 100))+ min_year = birthdate.replace(year=(birthdate.year + 10))+ today = datetime.date.today()+ if today > max_year or today < min_year:+ raise ValidationError(+ _('%(birthdate)s is not a valid birthdate'),+ params={'birthdate': birthdate},+ )+++ class UserProfile(models.Model):+ GENDER_MALE = '1'+ GENDER_FEMALE = '2'+ GENDER = (+ (GENDER_MALE, _('Male')),+ (GENDER_FEMALE, _('Female')),+ )++ INTENSITY_LOW = '1'+ INTENSITY_MEDIUM = '2'+ INTENSITY_HIGH = '3'+ INTENSITY = (+ (INTENSITY_LOW, _('Low')),+ (INTENSITY_MEDIUM, _('Medium')),+ (INTENSITY_HIGH, _('High')),+ )++ UNITS_KG = 'kg'+ UNITS_LB = 'lb'+ UNITS = (+ (UNITS_KG, _('Metric (kilogram)')),+ (UNITS_LB, _('Imperial (pound)')),+ )++ user = models.OneToOneField(+ User,+ editable=False,+ on_delete=models.CASCADE,+ )+ """+ The user+ """++ gym = models.ForeignKey(+ Gym,+ editable=False,+ null=True,+ blank=True,+ on_delete=models.SET_NULL,+ )+ """+ The gym this user belongs to, if any+ """+++ email_verified = models.BooleanField(default=False)++ """Flag indicating whether the user's email has been verified"""+++ is_temporary = models.BooleanField(default=False, editable=False)+ """+ Flag to mark a temporary user (demo account)+ """++ #+ # User preferences+ #++ show_comments = models.BooleanField(+ verbose_name=_('Show exercise comments'),+ help_text=_('Check to show exercise comments on the '+ 'workout view'),+ default=True,+ )+ """+ Show exercise comments on workout view+ """++ # Also show ingredients in english while composing a nutritional plan+ # (obviously this is only meaningful if the user has a language other than english)+ show_english_ingredients = models.BooleanField(+ verbose_name=_('Also use ingredients in English'),+ help_text=_(+ """Check to also show ingredients in English while creating+ a nutritional plan. These ingredients are extracted from a list provided+ by the US Department of Agriculture. It is extremely complete, with around+ 7000 entries, but can be somewhat overwhelming and make the search difficult."""+ ),+ default=True+ )++ workout_reminder_active = models.BooleanField(+ verbose_name=_('Activate workout reminders'),+ help_text=_(+ 'Check to activate automatic '+ 'reminders for workouts. You need '+ 'to provide a valid email for this '+ 'to work.'+ ),+ default=False+ )++ workout_reminder = IntegerField(+ verbose_name=_('Remind before expiration'),+ help_text=_('The number of days you want to be reminded '+ 'before a workout expires.'),+ default=14,+ validators=[MinValueValidator(1), MaxValueValidator(30)]+ )+ workout_duration = IntegerField(+ verbose_name=_('Default duration of workouts'),+ help_text=_(+ 'Default duration in weeks of workouts not '+ 'in a schedule. Used for email workout '+ 'reminders.'+ ),+ default=12,+ validators=[MinValueValidator(1), MaxValueValidator(30)]+ )+ last_workout_notification = models.DateField(editable=False, blank=False, null=True)+ """+ The last time the user got a workout reminder email++ This is needed e.g. to check daily per cron for old workouts but only+ send users an email once per week+ """++ notification_language = models.ForeignKey(+ Language,+ verbose_name=_('Notification language'),+ help_text=_(+ 'Language to use when sending you email '+ 'notifications, e.g. email reminders for '+ 'workouts. This does not affect the '+ 'language used on the website.'+ ),+ default=2,+ on_delete=models.CASCADE+ )+- timer_active = models.BooleanField(- verbose_name=_('Use pauses in workout timer'),- help_text=_('Check to activate timer pauses between '- 'exercises.'),- default=True- )- """- Switch to activate pauses in the gym view- """++ @property++ def is_trustworthy(self) -> bool:++ """++ Flag indicating whether the user "is trustworthy" and can submit or edit exercises+- timer_pause = IntegerField(- verbose_name=_('Default duration of workout pauses'),- help_text=_('Default duration in seconds of pauses used by '- 'the timer in the gym mode.'),- default=90,- validators=[MinValueValidator(10), MaxValueValidator(400)]- )- """- Default duration of workout pauses in the gym view- """++ At the moment the criteria are:++ - the account has existed for 3 weeks++ - the email address has been verified++ """++++ days_since_joined = datetime.date.today() - self.user.date_joined.date()++ minimum_account_age = 21++++ return days_since_joined.days > minimum_account_age and self.email_verified++++ @property++ def has_exercise_permission(self):++ """Returns true if user has all the exercise permissions and not just one."""++ # TODO: check if this can be removed / refactored++ if self.user.groups.filter(name='admin').exists() or self.user.groups.filter(++ name='exercises_editor').exists():++ return True++ return False++ #+ # User statistics+ #+ age = IntegerField(+ verbose_name=_('Age'),+ blank=False,+ null=True,+ validators=[MinValueValidator(10), MaxValueValidator(100)]+ )+ """The user's age"""++ birthdate = models.DateField(+ verbose_name=('Date of Birth'),+ blank=False,+ null=True,+ validators=[birthdate_validator],+ )+ """The user's date of birth"""++ height = IntegerField(+ verbose_name=_('Height (cm)'),+ blank=False,+ validators=[MinValueValidator(140), MaxValueValidator(230)],+ null=True+ )+ """The user's height"""++ gender = models.CharField(+ max_length=1,+ choices=GENDER,+ default=GENDER_MALE,+ blank=False,+ null=True,+ )+ """Gender"""++ sleep_hours = IntegerField(+ verbose_name=_('Hours of sleep'),+ help_text=_('The average hours of sleep per day'),+ default=7,+ blank=False,+ null=True,+ validators=[MinValueValidator(4), MaxValueValidator(10)]+ )+ """The average hours of sleep per day"""++ work_hours = IntegerField(+ verbose_name=_('Work'),+ help_text=_('Average hours per day'),+ default=8,+ blank=False,+ null=True,+ validators=[MinValueValidator(1), MaxValueValidator(15)]+ )+ """The average hours at work per day"""++ work_intensity = models.CharField(+ verbose_name=_('Physical intensity'),+ help_text=_('Approximately'),+ max_length=1,+ choices=INTENSITY,+ default=INTENSITY_LOW,+ blank=False,+ null=True+ )+ """Physical intensity of work"""++ sport_hours = IntegerField(+ verbose_name=_('Sport'),+ help_text=_('Average hours per week'),+ default=3,+ blank=False,+ null=True,+ validators=[MinValueValidator(1), MaxValueValidator(30)]+ )+ """The average hours performing sports per week"""++ sport_intensity = models.CharField(+ verbose_name=_('Physical intensity'),+ help_text=_('Approximately'),+ max_length=1,+ choices=INTENSITY,+ default=INTENSITY_MEDIUM,+ blank=False,+ null=True+ )+ """Physical intensity of sport activities"""++ freetime_hours = IntegerField(+ verbose_name=_('Free time'),+ help_text=_('Average hours per day'),+ default=8,+ blank=False,+ null=True,+ validators=[MinValueValidator(1), MaxValueValidator(15)]+ )+ """The average hours of free time per day"""++ freetime_intensity = models.CharField(+ verbose_name=_('Physical intensity'),+ help_text=_('Approximately'),+ max_length=1,+ choices=INTENSITY,+ default=INTENSITY_LOW,+ blank=False,+ null=True+ )+ """Physical intensity during free time"""++ calories = IntegerField(+ verbose_name=_('Total daily calories'),+ help_text=_('Total caloric intake, including e.g. any surplus'),+ default=2500,+ blank=False,+ null=True,+ validators=[MinValueValidator(1500), MaxValueValidator(5000)]+ )+ """Basic caloric intake based on physical activity"""++ #+ # Others+ #+ weight_unit = models.CharField(+ verbose_name=_('Weight unit'),+ max_length=2,+ choices=UNITS,+ default=UNITS_KG,+ )+ """Preferred weight unit"""++ ro_access = models.BooleanField(+ verbose_name=_('Allow external access'),+ help_text=_(+ 'Allow external users to access your workouts and '+ 'logs in a read-only mode. You need to set this '+ 'before you can share links e.g. to social media.'+ ),+ default=False+ )+ """Allow anonymous read-only access"""++ num_days_weight_reminder = models.IntegerField(+ verbose_name=_('Automatic reminders for weight '+ 'entries'),+ help_text=_('Number of days after the last '+ 'weight entry (enter 0 to '+ 'deactivate)'),+ validators=[MinValueValidator(0), MaxValueValidator(30)],+ default=0+ )+ """Number of Days for email weight reminder"""++ #+ # API+ #+ added_by = models.ForeignKey(+ User,+ editable=False,+ null=True,+ related_name='added_by',+ on_delete=models.CASCADE,+ )+ """User that originally registered this user via REST API"""++ can_add_user = models.BooleanField(default=False, editable=False)+ """+ Flag to indicate whether the (app) user can register other users on his+ behalf over the REST API+ """++ @property+ def weight(self):+ """+ Returns the last weight entry, done here to make the behaviour+ more consistent with the other settings (age, height, etc.)+ """+ try:+ weight = WeightEntry.objects.filter(user=self.user).latest().weight+ except WeightEntry.DoesNotExist:+ weight = 0+ return weight++ @property+ def address(self):+ """+ Return the address as saved in the current contract (user's gym)+ """+ out = {+ 'zip_code': '',+ 'city': '',+ 'street': '',+ 'phone': '',+ }+ if self.user.contract_member.exists():+ last_contract = self.user.contract_member.last()+ out['zip_code'] = last_contract.zip_code+ out['city'] = last_contract.city+ out['street'] = last_contract.street+ out['phone'] = last_contract.phone++ return out++ def clean(self):+ """+ Make sure the total amount of hours is 24+ """+ if (+ (self.sleep_hours and self.freetime_hours and self.work_hours)+ and (self.sleep_hours + self.freetime_hours + self.work_hours) > 24+ ):+ raise ValidationError(_('The sum of all hours has to be 24'))++ def __str__(self):+ """+ Return a more human-readable representation+ """+ return f"Profile for user {self.user}"++ @property+ def use_metric(self):+ """+ Simple helper that checks whether the user uses metric units or not+ :return: Boolean+ """+ return self.weight_unit == 'kg'++ def calculate_bmi(self):+ """+ Calculates the user's BMI++ Formula: weight/height^2+ - weight in kg+ - height in m+ """++ # If not all the data is available, return 0, otherwise the result+ # of the calculation below breaks django's template filters+ if not self.weight or not self.height:+ return 0++ weight = self.weight if self.use_metric else AbstractWeight(self.weight, 'lb').kg+ return weight / pow(self.height / decimal.Decimal(100), 2)++ def calculate_basal_metabolic_rate(self, formula=1):+ """+ Calculates the basal metabolic rate.++ Currently only the Mifflin-St.Jeor formula is supported+ """+ factor = 5 if self.gender == self.GENDER_MALE else -161+ weight = self.weight if self.use_metric else AbstractWeight(self.weight, 'lb').kg++ try:+ rate = (+ (10 * weight) # in kg+ + (decimal.Decimal(6.25) * self.height) # in cm+ - (5 * self.age) # in years+ + factor+ )+ # Any of the entries is missing+ except TypeError:+ rate = 0++ return decimal.Decimal(str(rate)).quantize(TWOPLACES)++ def calculate_activities(self):+ """+ Calculates the calories needed by additional physical activities++ Factors taken from+ * https://en.wikipedia.org/wiki/Physical_activity_level+ * http://www.fao.org/docrep/007/y5686e/y5686e07.htm+ """+ # Sleep+ sleep = self.sleep_hours * 0.95++ # Work+ if self.work_intensity == self.INTENSITY_LOW:+ work_factor = 1.5+ elif self.work_intensity == self.INTENSITY_MEDIUM:+ work_factor = 1.8+ else:+ work_factor = 2.2+ work = self.work_hours * work_factor++ # Sport (entered in hours/week, so we must divide)+ if self.sport_intensity == self.INTENSITY_LOW:+ sport_factor = 4+ elif self.sport_intensity == self.INTENSITY_MEDIUM:+ sport_factor = 6+ else:+ sport_factor = 10+ sport = (self.sport_hours / 7.0) * sport_factor++ # Free time+ if self.freetime_intensity == self.INTENSITY_LOW:+ freetime_factor = 1.3+ elif self.freetime_intensity == self.INTENSITY_MEDIUM:+ freetime_factor = 1.9+ else:+ freetime_factor = 2.4+ freetime = self.freetime_hours * freetime_factor++ # Total+ total = (sleep + work + sport + freetime) / 24.0+ return decimal.Decimal(str(total)).quantize(TWOPLACES)++ def user_bodyweight(self, weight):+ """+ Create a new weight entry as needed+ """+ if (+ not WeightEntry.objects.filter(user=self.user).exists() or (+ datetime.date.today() - WeightEntry.objects.filter(user=self.user).latest().date >+ datetime.timedelta(days=3)+ )+ ):+ entry = WeightEntry()+ entry.weight = weight+ entry.user = self.user+ entry.date = datetime.date.today()+ entry.save()++ # Update the last entry+ else:+ entry = WeightEntry.objects.filter(user=self.user).latest()+ entry.weight = weight+ entry.save()+ return entry++ def get_owner_object(self):+ """+ Returns the object that has owner information+ """+ return selfdiff --cc wger/core/tests/test_preferences.pyindex 782964b11,1f19afc8e..eef9cc228--- a/wger/core/tests/test_preferences.py+++ b/wger/core/tests/test_preferences.py@@@ -50,17 -50,22 +50,17 @@@ class PreferencesTestCase(WgerTestCase)self.assertTemplateUsed('preferences.html')# Change some preferences- response = self.client.post(- reverse('core:user:preferences'), {- 'show_comments': True,- 'show_english_ingredients': True,- 'email': '[email protected]',- 'workout_reminder_active': True,- 'workout_reminder': '30',- 'workout_duration': 12,- 'notification_language': 2,- 'timer_active': False,- 'timer_pause': 100,- 'num_days_weight_reminder': 10,- 'weight_unit': 'kg',- 'birthdate': '02/25/1987',- }- )+ response = self.client.post(reverse('core:user:preferences'),+ {'show_comments': True,+ 'show_english_ingredients': True,+ 'email': '[email protected]',+ 'workout_reminder_active': True,+ 'workout_reminder': '30',+ 'workout_duration': 12,+ 'notification_language': 2,+ 'num_days_weight_reminder': 10,+ 'weight_unit': 'kg',- 'birthdate': '02/25/1987'})++ 'birthdate': '02/25/1987',})self.assertEqual(response.status_code, 302)response = self.client.get(reverse('core:user:preferences'))@@@ -72,17 -77,22 +72,17 @@@self.assertEqual(User.objects.get(username='test').email, '[email protected]')# Change some preferences- response = self.client.post(- reverse('core:user:preferences'), {- 'show_comments': False,- 'show_english_ingredients': True,- 'email': '',- 'workout_reminder_active': True,- 'workout_reminder': 22,- 'workout_duration': 10,- 'notification_language': 2,- 'timer_active': True,- 'timer_pause': 40,- 'num_days_weight_reminder': 10,- 'weight_unit': 'lb',- 'birthdate': '02/25/1987',- }- )+ response = self.client.post(reverse('core:user:preferences'),+ {'show_comments': False,+ 'show_english_ingredients': True,+ 'email': '',+ 'workout_reminder_active': True,+ 'workout_reminder': 22,+ 'workout_duration': 10,+ 'notification_language': 2,+ 'num_days_weight_reminder': 10,+ 'weight_unit': 'lb',- 'birthdate': '02/25/1987'})++ 'birthdate': '02/25/1987',})self.assertEqual(response.status_code, 302)response = self.client.get(reverse('core:user:preferences'))diff --cc wger/core/urls.pyindex 298d6c5b8,6255aa452..4e03f3cf9--- a/wger/core/urls.py+++ b/wger/core/urls.py@@@ -57,52 -66,76 +66,52 @@@ patterns_language =# sub patterns for userpatterns_user = [- path(- 'login',- views.LoginView.as_view(template_name='user/login.html', authentication_form=UserLoginForm),- name='login',- ),- path(- 'logout',- user.logout,- name='logout',- ),- path(- 'delete',- user.delete,- name='delete',- ),- path(- '<int:user_pk>/delete',- user.delete,- name='delete',- ),- path(- '<int:user_pk>/trainer-login',- user.trainer_login,- name='trainer-login',- ),- path(- 'registration',- user.registration,- name='registration',- ),- path(- 'preferences',- user.preferences,- name='preferences',- ),- path(- 'api-key',- user.api_key,- name='api-key',- ),- path(- 'demo-entries',- misc.demo_entries,- name='demo-entries',- ),- path(- '<int:pk>/activate',- user.UserActivateView.as_view(),- name='activate',- ),- path(- '<int:pk>/deactivate',- user.UserDeactivateView.as_view(),- name='deactivate',- ),- path(- '<int:pk>/edit',- user.UserEditView.as_view(),- name='edit',- ),- path(- '<int:pk>/overview',- user.UserDetailView.as_view(),- name='overview',- ),- path(- 'list',- user.UserListView.as_view(),- name='list',- ),+ path('login',+ views.LoginView.as_view(template_name='user/login.html',+ authentication_form=UserLoginForm),+ name='login'),+ path('logout',+ user.logout,+ name='logout'),+ path('delete',+ user.delete,+ name='delete'),- path('confirm-email',- user.confirm_email,- name='confirm-email'),+ path('<int:user_pk>/delete',+ user.delete,+ name='delete'),++ path('confirm-email',++ user.confirm_email,++ name='confirm-email'),+ path('<int:user_pk>/trainer-login',+ user.trainer_login,+ name='trainer-login'),+ path('registration',+ user.registration,+ name='registration'),+ path('preferences',+ user.preferences,+ name='preferences'),+ path('api-key',+ user.api_key,+ name='api-key'),+ path('demo-entries',+ misc.demo_entries,+ name='demo-entries'),+ path('<int:pk>/activate',+ user.UserActivateView.as_view(),+ name='activate'),+ path('<int:pk>/deactivate',+ user.UserDeactivateView.as_view(),+ name='deactivate'),+ path('<int:pk>/edit',+ user.UserEditView.as_view(),+ name='edit'),+ path('<int:pk>/overview',+ user.UserDetailView.as_view(),+ name='overview'),+ path('list',+ user.UserListView.as_view(),+ name='list'),# Password reset is implemented by Django, no need to cook our own soup here# (besides the templates)diff --cc wger/core/views/user.pyindex 05bca8c61,061292ab0..818038087--- a/wger/core/views/user.py+++ b/wger/core/views/user.py@@@ -70,9 -70,8 +70,9 @@@ from crispy_forms.layout importColumn,Layout,Row,- Submit+ Submit,)+from django_email_verification import send_emailfrom rest_framework.authtoken.models import Token# wgerdiff --cc wger/exercises/api/serializers.pyindex fc8fbdb1a,31b412434..68a3af550--- a/wger/exercises/api/serializers.py+++ b/wger/exercises/api/serializers.py@@@ -27,7 -26,6 +27,7 @@@ from wger.exercises.models importExerciseComment,ExerciseImage,Muscle,- Variation++ Variation,)@@@ -74,34 -81,16 +77,37 @@@ class ExerciseCommentSerializer(seriali"""ExerciseComment serializer"""+class Meta:model = ExerciseComment- fields = ['id',- 'exercise',- 'comment']+ fields = [+ 'id',+ 'exercise',+ 'comment',+ ]+class ExerciseAliasSerializer(serializers.ModelSerializer):+ """+ ExerciseAlias serializer+ """+ class Meta:+ model = ExerciseAlias+ fields = ['id',+ 'exercise',+ 'alias']+++class ExerciseInfoAliasSerializer(serializers.ModelSerializer):+ """+ Exercise alias serializer for info endpoint+ """+ class Meta:+ model = ExerciseAlias+ fields = ['id',+ 'alias']++class ExerciseCategorySerializer(serializers.ModelSerializer):"""ExerciseCategory serializerdiff --cc wger/exercises/api/views.pyindex caa714ee1,883b3405d..12816053b--- a/wger/exercises/api/views.py+++ b/wger/exercises/api/views.py@@@ -56,10 -50,12 +56,13 @@@ from wger.exercises.models importExerciseCategory,ExerciseComment,ExerciseImage,- Muscle+ Muscle,+ )+ from wger.utils.language import (+ load_item_languages,+ load_language,)- from wger.utils.language import load_item_languages+from wger.utils.models import AbstractSubmissionModelfrom wger.utils.permissions import CreateOnlyPermission@@@ -75,28 -71,32 +78,32 @@@ class ExerciseBaseViewSet(viewsets.Readserializer_class = ExerciseBaseSerializerpermission_classes = (IsAuthenticatedOrReadOnly, CreateOnlyPermission)ordering_fields = '__all__'- filterset_fields = ('category',- 'muscles',- 'muscles_secondary',- 'equipment')+ filterset_fields = (+ 'category',+ 'muscles',+ 'muscles_secondary',+ 'equipment',+ )-class ExerciseViewSet(viewsets.ReadOnlyModelViewSet):+class ExerciseViewSet(CreateUpdateModelViewSet):"""API endpoint for exercise objects. For a read-only endpoint with allthe information of an exercise, see /api/v2/exerciseinfo/"""queryset = Exercise.objects.accepted()serializer_class = ExerciseSerializer- permission_classes = (IsAuthenticatedOrReadOnly, CreateOnlyPermission)+ permission_classes = (CanEditExercises, )ordering_fields = '__all__'- filterset_fields = ('uuid',- 'creation_date',- 'exercise_base',- 'description',- 'language',- 'status',- 'name')+ filterset_fields = (+ 'uuid',+ 'creation_date',+ 'exercise_base',+ 'description',+ 'language',+ 'status',+ 'name',+ )def perform_create(self, serializer):"""@@@ -278,23 -237,24 +287,25 @@@ class ExerciseCategoryViewSet(viewsets.queryset = ExerciseCategory.objects.all()serializer_class = ExerciseCategorySerializerordering_fields = '__all__'- filterset_fields = ('name',)+ filterset_fields = ('name', )-class ExerciseImageViewSet(viewsets.ModelViewSet):+class ExerciseImageViewSet(CreateUpdateModelViewSet):"""API endpoint for exercise image objects"""+queryset = ExerciseImage.objects.all()serializer_class = ExerciseImageSerializer- permission_classes = (IsAuthenticatedOrReadOnly, CreateOnlyPermission)+ permission_classes = (CanEditExercises, )ordering_fields = '__all__'- filterset_fields = ('is_main',- 'status',- 'exercise_base',- 'license',- 'license_author')+ filterset_fields = (+ 'is_main',+ 'status',+ 'exercise_base',+ 'license',+ 'license_author',+ )@action(detail=True)def thumbnails(self, request, pk):@@@ -331,10 -291,8 +342,9 @@@ class ExerciseCommentViewSet(CreateUpdaAPI endpoint for exercise comment objects"""serializer_class = ExerciseCommentSerializer+ permission_classes = (CanEditExercises,)ordering_fields = '__all__'- filterset_fields = ('comment',- 'exercise')+ filterset_fields = ('comment', 'exercise')def get_queryset(self):"""Filter by language for exercise comments"""diff --cc wger/exercises/models/__init__.pyindex 000000000,490907068..9032c7bacmode 000000,100644..100644--- a/wger/exercises/models/__init__.py+++ b/wger/exercises/models/__init__.py@@@ -1,0 -1,25 +1,26 @@@+ # 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/>.++ # Local++from .alias import ExerciseAlias+ from .base import ExerciseBase+ from .category import ExerciseCategory+ from .comment import ExerciseComment+ from .equipment import Equipment+ from .exercise import Exercise+ from .image import ExerciseImage+ from .muscle import Muscle+ from .variation import Variationdiff --cc wger/exercises/models/alias.pyindex 000000000,000000000..2dfe0b8a3new file mode 100644--- /dev/null+++ b/wger/exercises/models/alias.py@@@ -1,0 -1,0 +1,61 @@@++# 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/>.++++# Django++from django.db import models++from django.utils.translation import gettext_lazy as _++++# Third Party++from simple_history.models import HistoricalRecords++++# wger++from wger.utils.cache import reset_workout_canonical_form++++from .exercise import Exercise++++class ExerciseAlias(models.Model):++ """++ Model for an exercise (name)alias++ """++ exercise = models.ForeignKey(Exercise,++ verbose_name=_('Exercise'),++ on_delete=models.CASCADE)++ alias = models.CharField(max_length=200,++ verbose_name=_('Alias for an exercise'),)++++ history = HistoricalRecords()++ """Edit history"""++++ def __str__(self):++ """++ Return a more human-readable representation++ """++ return self.alias++++ def delete(self, *args, **kwargs):++ """++ Reset cached workouts++ """++ for setting in self.exercise.setting_set.all():++ reset_workout_canonical_form(setting.set.exerciseday.training.pk)++++ super(ExerciseAlias, self).delete(*args, **kwargs)++++ def get_owner_object(self):++ """++ Comment has no owner information++ """++ return Falsediff --cc wger/exercises/models/base.pyindex 000000000,6427f6b63..94c82c948mode 000000,100644..100644--- a/wger/exercises/models/base.py+++ b/wger/exercises/models/base.py@@@ -1,0 -1,95 +1,100 @@@+ # 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 uuid++ # Django+ from django.db import models+ from django.utils.translation import gettext_lazy as _++ # wger++from simple_history.models import HistoricalRecords+++ from wger.utils.managers import SubmissionManager+ from wger.utils.models import (+ AbstractLicenseModel,+ AbstractSubmissionModel,+ )++ # Local+ from .category import ExerciseCategory+ from .equipment import Equipment+ from .muscle import Muscle+ from .variation import Variation+++ class ExerciseBase(AbstractSubmissionModel, AbstractLicenseModel, models.Model):+ """+ Model for an exercise base+ """++ objects = SubmissionManager()+ """Custom manager"""++ uuid = models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')+ """Globally unique ID, to identify the base across installations"""++ category = models.ForeignKey(+ ExerciseCategory,+ verbose_name=_('Category'),+ on_delete=models.CASCADE,+ )++ muscles = models.ManyToManyField(+ Muscle,+ blank=True,+ verbose_name=_('Primary muscles'),+ )+ """Main muscles trained by the exercise"""++ muscles_secondary = models.ManyToManyField(+ Muscle,+ verbose_name=_('Secondary muscles'),+ related_name='secondary_muscles_base',+ blank=True,+ )+ """Secondary muscles trained by the exercise"""++ equipment = models.ManyToManyField(+ Equipment,+ verbose_name=_('Equipment'),+ blank=True,+ )+ """Equipment needed by this exercise"""++ variations = models.ForeignKey(+ Variation,+ verbose_name=_('Variations'),+ on_delete=models.CASCADE,+ null=True,+ blank=True,+ )+ """Variations of this exercise"""+++ history = HistoricalRecords()++ """Edit history"""+++ #+ # Own methods+ #++ @property+ def get_languages(self):+ """+ Returns the languages from the exercises that use this base+ """+ return [exercise.language for exercise in self.exercises.all()]diff --cc wger/exercises/models/comment.pyindex 000000000,2fa0179fb..94cef21e5mode 000000,100644..100644--- a/wger/exercises/models/comment.py+++ b/wger/exercises/models/comment.py@@@ -1,0 -1,72 +1,77 @@@+ # 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/>.++ # Django+ from django.db import models+ from django.utils.translation import gettext_lazy as _++ # wger+ from wger.utils.cache import reset_workout_canonical_form+++from simple_history.models import HistoricalRecords+++ # Local+ from .exercise import Exercise+++ class ExerciseComment(models.Model):+ """+ Model for an exercise comment+ """+ exercise = models.ForeignKey(+ Exercise,+ verbose_name=_('Exercise'),+ editable=False,+ on_delete=models.CASCADE,+ )+ comment = models.CharField(+ max_length=200,+ verbose_name=_('Comment'),+ help_text=_('A comment about how to correctly do this exercise.')+ )+++ history = HistoricalRecords()++ """Edit history"""+++ def __str__(self):+ """+ Return a more human-readable representation+ """+ return self.comment++ def save(self, *args, **kwargs):+ """+ Reset cached workouts+ """+ for setting in self.exercise.setting_set.all():+ reset_workout_canonical_form(setting.set.exerciseday.training_id)++ super(ExerciseComment, self).save(*args, **kwargs)++ def delete(self, *args, **kwargs):+ """+ Reset cached workouts+ """+ for setting in self.exercise.setting_set.all():+ reset_workout_canonical_form(setting.set.exerciseday.training.pk)++ super(ExerciseComment, self).delete(*args, **kwargs)++ def get_owner_object(self):+ """+ Comment has no owner information+ """+ return Falsediff --cc wger/exercises/models/exercise.pyindex 000000000,8b3302017..794a91f60mode 000000,100644..100644--- a/wger/exercises/models/exercise.py+++ b/wger/exercises/models/exercise.py@@@ -1,0 -1,269 +1,274 @@@+ # 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 uuid++ # Django+ from django.conf import settings+ from django.contrib.auth.models import User+ from django.contrib.sites.models import Site+ from django.core import mail+ from django.core.validators import MinLengthValidator+ from django.db import models+ from django.template.loader import render_to_string+ from django.urls import reverse+ from django.utils import translation+ from django.utils.text import slugify+ from django.utils.translation import gettext_lazy as _++ # Third Party+ import bleach++ # wger++from simple_history.models import HistoricalRecords+++ from wger.core.models import Language+ from wger.exercises.models import ExerciseBase+ from wger.utils.cache import (+ delete_template_fragment_cache,+ reset_workout_canonical_form,+ )+ from wger.utils.helpers import smart_capitalize+ from wger.utils.managers import SubmissionManager+ from wger.utils.models import (+ AbstractLicenseModel,+ AbstractSubmissionModel,+ )+++ class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):+ """+ Model for an exercise+ """++ objects = SubmissionManager()+ """Custom manager"""++ description = models.TextField(+ max_length=2000,+ verbose_name=_('Description'),+ validators=[MinLengthValidator(40)],+ )+ """Description on how to perform the exercise"""++ name = models.CharField(max_length=200, verbose_name=_('Name'))+ """The exercise's name, with correct uppercase"""++ name_original = models.CharField(+ max_length=200,+ verbose_name=_('Name'),+ default='',+ )+ """The exercise's name, as entered by the user"""++ creation_date = models.DateField(+ _('Date'),+ auto_now_add=True,+ null=True,+ blank=True,+ )+ """The submission date"""++ language = models.ForeignKey(+ Language,+ verbose_name=_('Language'),+ on_delete=models.CASCADE,+ )+ """The exercise's language"""++ uuid = models.UUIDField(+ default=uuid.uuid4,+ editable=False,+ verbose_name='UUID',+ )+ """Globally unique ID, to identify the exercise across installations"""++ exercise_base = models.ForeignKey(+ ExerciseBase,+ verbose_name='ExerciseBase',+ on_delete=models.CASCADE,+ default=None,+ null=True,+ related_name='exercises',+ )+ """ Refers to the base exercise with non translated information """+++ history = HistoricalRecords()++ """Edit history"""+++ #+ # Django methods+ #+ class Meta:+ base_manager_name = 'objects'+ ordering = [+ "name",+ ]++ def get_absolute_url(self):+ """+ Returns the canonical URL to view an exercise+ """+ return reverse('exercise:exercise:view', kwargs={'id': self.id, 'slug': slugify(self.name)})++ def save(self, *args, **kwargs):+ """+ Reset all cached infos+ """+ self.name = smart_capitalize(self.name_original)+ super(Exercise, self).save(*args, **kwargs)++ # Cached template fragments+ for language in Language.objects.all():+ delete_template_fragment_cache('muscle-overview', language.id)+ delete_template_fragment_cache('exercise-overview', language.id)+ delete_template_fragment_cache('equipment-overview', language.id)++ # Cached workouts+ for setting in self.setting_set.all():+ reset_workout_canonical_form(setting.set.exerciseday.training_id)++ def delete(self, *args, **kwargs):+ """+ Reset all cached infos+ """++ # Cached template fragments+ for language in Language.objects.all():+ delete_template_fragment_cache('muscle-overview', language.id)+ delete_template_fragment_cache('exercise-overview', language.id)+ delete_template_fragment_cache('equipment-overview', language.id)++ # Cached workouts+ for setting in self.setting_set.all():+ reset_workout_canonical_form(setting.set.exerciseday.training.pk)++ super(Exercise, self).delete(*args, **kwargs)++ def __str__(self):+ """+ Return a more human-readable representation+ """+ return self.name++ #+ # Properties to expose the info from the exercise base+ #+ @property+ def category(self):+ return self.exercise_base.category++ @property+ def muscles(self):+ return self.exercise_base.muscles++ @property+ def muscles_secondary(self):+ return self.exercise_base.muscles_secondary++ @property+ def equipment(self):+ return self.exercise_base.equipment++ @property+ def images(self):+ return self.exercise_base.exerciseimage_set++ @property+ def variations(self):+ """+ Returns the variations for this exercise in the same language+ """+ out = []+ if self.exercise_base.variations:+ for variation in self.exercise_base.variations.exercisebase_set.all():+ for exercise in variation.exercises.filter(language=self.language).accepted():+ out.append(exercise)+ return out++ #+ # Own methods+ #+ @property+ def main_image(self):+ """+ Return the main image for the exercise or None if nothing is found+ """+ return self.images.accepted().filter(is_main=True).first()++ @property+ def description_clean(self):+ """+ Return the exercise description with all markup removed+ """+ return bleach.clean(self.description, strip=True)++ def get_owner_object(self):+ """+ Exercise has no owner information+ """+ return False++ def send_email(self, request):+ """+ Sends an email after being successfully added to the database (for user+ submitted exercises only)+ """+ try:+ user = User.objects.get(username=self.license_author)+ except User.DoesNotExist:+ return+ if self.license_author and user.email:+ translation.activate(user.userprofile.notification_language.short_name)+ url = request.build_absolute_uri(self.get_absolute_url())+ subject = _('Exercise was successfully added to the general database')+ context = {+ 'exercise': self.name,+ 'url': url,+ 'site': Site.objects.get_current().domain,+ }+ message = render_to_string('exercise/email_new.tpl', context)+ mail.send_mail(+ subject,+ message,+ settings.WGER_SETTINGS['EMAIL_FROM'], [user.email],+ fail_silently=True+ )++ def set_author(self, request):+ """+ Set author and status+ This is only used when creating exercises (via web or API)+ """++ if request.user.has_perm('exercises.add_exercise'):+ self.status = self.STATUS_ACCEPTED+ if not self.license_author:+ self.license_author = request.get_host().split(':')[0]+ else:+ if not self.license_author:+ self.license_author = request.user.username++ subject = _('New user submitted exercise')++ message = _('The user {0} submitted a new exercise "{1}".'+ ).format(request.user.username, self.name_original)+ mail.mail_admins(+ str(subject),+ str(message),+ fail_silently=True,+ )diff --cc wger/exercises/urls.pyindex f878a83ad,c6a7f0de7..d436b827c--- a/wger/exercises/urls.py+++ b/wger/exercises/urls.py@@@ -31,34 -31,36 +31,44 @@@ from wger.exercises.views importexercises,images,muscles,- history++ history,)+# sub patterns for history+patterns_history = [+ path('overview/',+ history.overview,+ name='overview'),+]+# sub patterns for musclespatterns_muscle = [- path('overview/',- muscles.MuscleListView.as_view(),- name='overview'),- path('admin-overview/',- muscles.MuscleAdminListView.as_view(),- name='admin-list'),- path('add/',- muscles.MuscleAddView.as_view(),- name='add'),- path('<int:pk>/edit/',- muscles.MuscleUpdateView.as_view(),- name='edit'),- path('<int:pk>/delete/',- muscles.MuscleDeleteView.as_view(),- name='delete'),+ path(+ 'overview/',+ muscles.MuscleListView.as_view(),+ name='overview',+ ),+ path(+ 'admin-overview/',+ muscles.MuscleAdminListView.as_view(),+ name='admin-list',+ ),+ path(+ 'add/',+ muscles.MuscleAddView.as_view(),+ name='add',+ ),+ path(+ '<int:pk>/edit/',+ muscles.MuscleUpdateView.as_view(),+ name='edit',+ ),+ path(+ '<int:pk>/delete/',+ muscles.MuscleDeleteView.as_view(),+ name='delete',+ ),]# sub patterns for exercise imagesdiff --cc wger/settings_global.pyindex a1061b74a,961a19a0d..f638aa03a--- a/wger/settings_global.py+++ b/wger/settings_global.py@@@ -87,15 -87,8 +87,14 @@@ INSTALLED_APPS =# CORS'corsheaders',++ # History keeping+ 'simple_history',++ # Django email verification+ 'django_email_verification',)-MIDDLEWARE = ('corsheaders.middleware.CorsMiddleware','django.middleware.common.CommonMiddleware',diff --cc wger/urls.pyindex ea8eed48e,389105c7e..f2543f618--- a/wger/urls.py+++ b/wger/urls.py@@@ -148,17 -164,21 +160,20 @@@ urlpatterns +=path('api/v2/', include(router.urls)),# The api user login- path('api/v2/login/', core_api_views.UserAPILoginView.as_view({- 'post': 'post'}), name='api_user'),- path('api/v2/register/', core_api_views.UserAPIRegistrationViewSet.as_view({- 'post': 'post'}), name='api_register'),+ path(+ 'api/v2/login/', core_api_views.UserAPILoginView.as_view({'post': 'post'}), name='api_user'+ ),+ path(+ 'api/v2/register/',+ core_api_views.UserAPIRegistrationViewSet.as_view({'post': 'post'}),+ name='api_register'+ ),# Others- path(- 'api/v2/version/',- core_api_views.ApplicationVersionView.as_view({'get': 'get'}),- name='app_version'- ),+ path('api/v2/version/', core_api_views.ApplicationVersionView.as_view({+ 'get': 'get'}), name='app_version'),-+ path('email/', include(email_urls)),+]#