Self hosted FLOSS fitness/workout, nutrition and weight tracker
Start working on self-hosted videos for exercises
Roland Geider6aeb96443802
diff --git a/wger/core/fixtures/groups.json b/wger/core/fixtures/groups.jsonindex b81165963..5c944763f 100644--- a/wger/core/fixtures/groups.json+++ b/wger/core/fixtures/groups.json@@ -168,6 +168,21 @@"exercises","exerciseimage"],+ [+ "add_exercisevideo",+ "exercises",+ "exercisevideo"+ ],+ [+ "change_exercisevideo",+ "exercises",+ "exercisevideo"+ ],+ [+ "delete_exercisevideo",+ "exercises",+ "exercisevideo"+ ],["add_muscle","exercises",diff --git a/wger/exercises/forms.py b/wger/exercises/forms.pyindex 0db52a2a6..5cfd2e992 100644--- a/wger/exercises/forms.py+++ b/wger/exercises/forms.py@@ -21,6 +21,7 @@ from django import formsfrom wger.exercises.models import (ExerciseComment,ExerciseImage,+ ExerciseVideo,)@@ -37,6 +38,18 @@ class ExerciseImageForm(forms.ModelForm):)+class ExerciseVideoForm(forms.ModelForm):++ class Meta:+ model = ExerciseVideo+ fields = (+ 'video',+ 'is_main',+ 'license',+ 'license_author',+ )++class CommentForm(forms.ModelForm):class Meta:diff --git a/wger/exercises/migrations/0015_exercise_videos.py b/wger/exercises/migrations/0015_exercise_videos.pynew file mode 100644index 000000000..f4b8ac00b--- /dev/null+++ b/wger/exercises/migrations/0015_exercise_videos.py@@ -0,0 +1,37 @@+# Generated by Django 3.2.10 on 2022-01-20 21:27++from django.db import migrations, models+import django.db.models.deletion+import uuid+import wger.exercises.models.video+++class Migration(migrations.Migration):++ dependencies = [+ ('core', '0013_auto_20210726_1729'),+ ('exercises', '0014_exerciseimage_style'),+ ]++ operations = [+ migrations.AlterField(+ model_name='exerciseimage',+ name='style',+ field=models.CharField(choices=[('1', 'Line'), ('2', '3D'), ('3', 'Low-poly'), ('4', 'Photo'), ('5', 'Other')], default='4', help_text='The art style of your image', max_length=1),+ ),+ migrations.CreateModel(+ name='ExerciseVideo',+ 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')),+ ('video', models.FileField(upload_to=wger.exercises.models.video.exercise_video_upload_dir, verbose_name='Video')),+ ('is_main', models.BooleanField(default=False, verbose_name='Main video')),+ ('exercise_base', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='exercises.exercisebase', verbose_name='Exercise')),+ ('license', models.ForeignKey(default=2, on_delete=django.db.models.deletion.CASCADE, to='core.license', verbose_name='License')),+ ],+ options={+ 'ordering': ['-is_main', 'id'],+ },+ ),+ ]diff --git a/wger/exercises/models/__init__.py b/wger/exercises/models/__init__.pyindex 490907068..af78f086c 100644--- a/wger/exercises/models/__init__.py+++ b/wger/exercises/models/__init__.py@@ -23,3 +23,4 @@ from .exercise import Exercisefrom .image import ExerciseImagefrom .muscle import Musclefrom .variation import Variation+from .video import ExerciseVideodiff --git a/wger/exercises/models/exercise.py b/wger/exercises/models/exercise.pyindex 8b3302017..3ba031e82 100644--- a/wger/exercises/models/exercise.py+++ b/wger/exercises/models/exercise.py@@ -183,6 +183,10 @@ class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):def images(self):return self.exercise_base.exerciseimage_set+ @property+ def videos(self):+ return self.exercise_base.exercisevideo_set+@propertydef variations(self):"""diff --git a/wger/exercises/models/video.py b/wger/exercises/models/video.pynew file mode 100644index 000000000..8da780fb7--- /dev/null+++ b/wger/exercises/models/video.py@@ -0,0 +1,79 @@+# 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.exercises.models import ExerciseBase+from wger.utils.models import AbstractLicenseModel+++def exercise_video_upload_dir(instance, filename):+ """+ Returns the upload target for exercise videos+ """+ ext = pathlib.Path(filename).suffix+ return "exercise-video/{0}/{1}{2}".format(instance.exercise_base.id, instance.uuid, ext)+++class ExerciseVideo(AbstractLicenseModel, models.Model):+ """+ Model for an exercise image+ """++ uuid = models.UUIDField(+ default=uuid.uuid4,+ editable=False,+ verbose_name='UUID',+ )+ """Globally unique ID, to identify the image across installations"""++ exercise_base = models.ForeignKey(+ ExerciseBase,+ verbose_name=_('Exercise'),+ on_delete=models.CASCADE,+ )+ """The exercise the image belongs to"""++ video = models.FileField(+ verbose_name=_('Video'),+ upload_to=exercise_video_upload_dir,+ )+ """Uploaded video"""++ is_main = models.BooleanField(+ verbose_name=_('Main video'),+ default=False,+ )+ """A flag indicating whether the image is the exercise's main image"""++ class Meta:+ """+ Set default ordering+ """+ ordering = ['-is_main', 'id']++ def get_owner_object(self):+ """+ Image has no owner information+ """+ return Falsediff --git a/wger/exercises/templates/exercise/view.html b/wger/exercises/templates/exercise/view.htmlindex 11eb41823..d62f0b2de 100644--- a/wger/exercises/templates/exercise/view.html+++ b/wger/exercises/templates/exercise/view.html@@ -92,7 +92,7 @@ $(document).ready(function() {{# Images #}{% with images=exercise.images.accepted %}-{% if images or perms.exercises.change_exerciseimage %}+{% if images or perms.exercises.change_exerciseimage %}<h5 class="mt-4">{% translate "Images" %}:</h5><div class="row row-cols-2 row-cols-md-3">{% with other_images=images %}@@ -141,6 +141,27 @@ $(document).ready(function() {{% endif %}{% endwith %}++{# Videos #}+{% with videos=exercise.videos.all %}+{% if videos or perms.exercises.change_exercisevideos %}+ {% for video in videos %}+ <video width='400' controls>+ <source src='{{ MEDIA_URL }}{{ video.video }}' type='video/mp4'>+ Your browser does not support the video tag.+ </video>+ {% endfor %}++ {% if perms.exercises.change_exercisevideo %}+ <p>+ <a href="{% url 'exercise:video:add' exercise.id %}" >+ {% translate "Add new video" %}+ </a>+ </p>+ {% endif %}+{% endif %}+{% endwith %}+{% if perms.exercises.change_exerciseimage %}{% with images=exercise.images.pending %}{% if images %}diff --git a/wger/exercises/urls.py b/wger/exercises/urls.pyindex c6a7f0de7..b972b94f5 100644--- a/wger/exercises/urls.py+++ b/wger/exercises/urls.py@@ -31,6 +31,7 @@ from wger.exercises.views import (exercises,images,muscles,+ videos,)@@ -92,6 +93,25 @@ patterns_images = [),]+# sub patterns for exercise videos+patterns_videos = [+ path(+ '<int:exercise_pk>/video/add',+ videos.ExerciseVideoAddView.as_view(),+ name='add',+ ),+ path(+ '<int:pk>/edit',+ videos.ExerciseVideoEditView.as_view(),+ name='edit',+ ),+ path(+ '<int:exercise_pk>/image/<int:pk>/delete',+ videos.ExerciseVideoDeleteView.as_view(),+ name='delete',+ ),+]+# sub patterns for exercise commentspatterns_comment = [path(@@ -221,6 +241,7 @@ patterns_exercise = [urlpatterns = [path('muscle/', include((patterns_muscle, 'muscle'), namespace="muscle")),path('image/', include((patterns_images, 'image'), namespace="image")),+ path('video/', include((patterns_videos, 'image'), namespace="video")),path('comment/', include((patterns_comment, 'comment'), namespace="comment")),path('category/', include((patterns_category, 'category'), namespace="category")),path('equipment/', include((patterns_equipment, 'equipment'), namespace="equipment")),diff --git a/wger/exercises/views/videos.py b/wger/exercises/views/videos.pynew file mode 100644index 000000000..86a69e11d--- /dev/null+++ b/wger/exercises/views/videos.py@@ -0,0 +1,146 @@+# -*- 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++# Standard Library+import logging++# Django+from django.contrib.auth.decorators import permission_required+from django.contrib.auth.mixins import (+ LoginRequiredMixin,+ PermissionRequiredMixin,+)+from django.http import HttpResponseRedirect+from django.shortcuts import get_object_or_404+from django.urls import reverse+from django.utils.translation import (+ gettext as _,+ gettext_lazy,+)+from django.views.generic import (+ CreateView,+ DeleteView,+ UpdateView,+)++# wger+from wger.exercises.forms import (+ ExerciseImageForm,+ ExerciseVideoForm,+)+from wger.exercises.models import (+ Exercise,+ ExerciseVideo,+)+from wger.utils.generic_views import (+ WgerDeleteMixin,+ WgerFormMixin,+)+++logger = logging.getLogger(__name__)+"""+Exercise videos+"""+++class ExerciseVideoEditView(+ WgerFormMixin,+ LoginRequiredMixin,+ PermissionRequiredMixin,+ UpdateView,+):+ """+ Generic view to update an existing exercise video+ """++ model = ExerciseVideo+ title = gettext_lazy('Edit')+ permission_required = 'exercises.change_exercisevideo'+ form_class = ExerciseVideoForm++ def get_success_url(self):+ return reverse('exercise:exercise:view', kwargs={'id': self.object.exercise_base.id})++ # Send some additional data to the template+ def get_context_data(self, **kwargs):+ context = super(ExerciseVideoEditView, self).get_context_data(**kwargs)+ context['enctype'] = 'multipart/form-data'+ return context+++class ExerciseVideoAddView(+ WgerFormMixin,+ LoginRequiredMixin,+ PermissionRequiredMixin,+ CreateView,+):+ """+ Generic view to add a new exercise video+ """++ model = ExerciseVideo+ title = gettext_lazy('Add new video')+ permission_required = 'exercises.add_exercisevideo'+ form_class = ExerciseVideoForm++ def form_valid(self, form):+ """Set the exercise base and the author"""+ exercise = get_object_or_404(Exercise, pk=self.kwargs['exercise_pk'])+ form.instance.exercise_base = exercise.exercise_base+ return super(ExerciseVideoAddView, self).form_valid(form)++ def get_success_url(self):+ return reverse('exercise:exercise:view', kwargs={'id': self.kwargs['exercise_pk']})++ def get_context_data(self, **kwargs):+ """+ Send some additional data to the template+ """+ context = super(ExerciseVideoAddView, self).get_context_data(**kwargs)+ context['enctype'] = 'multipart/form-data'+ return context+++class ExerciseVideoDeleteView(+ WgerDeleteMixin,+ LoginRequiredMixin,+ PermissionRequiredMixin,+ DeleteView,+):+ """+ Generic view to delete an existing exercise image+ """++ model = ExerciseVideo+ fields = ('video', 'is_main')+ messages = gettext_lazy('Successfully deleted')+ permission_required = 'exercises.delete_exercisevideo'++ def get_success_url(self):+ """+ Return to exercise image+ """+ return reverse('exercise:exercise:view', kwargs={'id': self.kwargs['exercise_pk']})++ def get_context_data(self, **kwargs):+ """+ Send some additional data to the template+ """+ context = super(ExerciseVideoDeleteView, self).get_context_data(**kwargs)++ context['title'] = _('Delete?')+ return context