Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add validator for check for valid videos, some more polishing

Roland Geidera6151be5a1c7
diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.py
index b139bb4c7..d25200914 100644
--- a/wger/exercises/api/views.py
+++ b/wger/exercises/api/views.py
@@ -41,8 +41,8 @@ from wger.exercises.api.serializers import (
ExerciseCommentSerializer,
ExerciseImageSerializer,
ExerciseInfoSerializer,
- ExerciseVideoSerializer,
ExerciseSerializer,
+ ExerciseVideoSerializer,
MuscleSerializer,
)
from wger.exercises.models import (
diff --git a/wger/exercises/fixtures/test-exercise-videos.json b/wger/exercises/fixtures/test-exercise-videos.json
new file mode 100644
index 000000000..4c1993ffa
--- /dev/null
+++ b/wger/exercises/fixtures/test-exercise-videos.json
@@ -0,0 +1,45 @@
+[
+ {
+ "pk": 1,
+ "model": "exercises.exercisevideo",
+ "fields": {
+ "image": "exercise-images/1/protestschwein.jpg",
+ "exercise_base": 1,
+ "is_main": true,
+ "license": "1",
+ "license_author": "",
+ "height": 640,
+ "width": 480,
+ "duration": "13.5",
+ "codec": "h264"
+ }
+ },
+ {
+ "pk": 2,
+ "model": "exercises.exercisevideo",
+ "fields": {
+ "image": "exercise-images/1/wildschwein.jpg",
+ "exercise_base": 1,
+ "is_main": false,
+ "license": "2",
+ "height": 640,
+ "width": 480,
+ "duration": "20",
+ "codec": "h264"
+ }
+ },
+ {
+ "pk": 3,
+ "model": "exercises.exercisevideo",
+ "fields": {
+ "image": "exercise-images/1/wildschwein.jpg",
+ "exercise_base": 2,
+ "is_main": false,
+ "license": "2",
+ "height": 640,
+ "width": 480,
+ "duration": "120.1465",
+ "codec": "h264"
+ }
+ }
+]
diff --git a/wger/exercises/management/commands/download-exercise-videos.py b/wger/exercises/management/commands/download-exercise-videos.py
new file mode 100644
index 000000000..c89b332a7
--- /dev/null
+++ b/wger/exercises/management/commands/download-exercise-videos.py
@@ -0,0 +1,140 @@
+# -*- 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 os
+
+# Django
+from django.conf import settings
+from django.core.exceptions import (
+ ImproperlyConfigured,
+ ValidationError,
+)
+from django.core.files import File
+from django.core.files.temp import NamedTemporaryFile
+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.exercises.models import (
+ ExerciseBase,
+ ExerciseVideo,
+)
+
+
+IMAGE_API = "{0}/api/v2/video/"
+
+
+class Command(BaseCommand):
+ """
+ Download exercise videos from wger.de and updates the local database
+
+ Both the exercises and the videos are identified by their UUID, which can't
+ be modified via the GUI.
+ """
+
+ help = ('Download exercise videos from wger.de and update the local database')
+
+ 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('wger/{} + requests'.format(get_version()))}
+
+ # Get all images
+ page = 1
+ all_videos_processed = False
+ result = requests.get(IMAGE_API.format(remote_url), headers=headers).json()
+ self.stdout.write('*** Processing videos ***')
+ while not all_videos_processed:
+ self.stdout.write('')
+ self.stdout.write(f'*** Page {page}')
+ self.stdout.write('')
+
+ for video_data in result['results']:
+ video_uuid = video_data['uuid']
+
+ self.stdout.write(f'Processing video {video_uuid}')
+
+ try:
+ exercise_base = ExerciseBase.objects.get(id=video_data['exercise_base'])
+ except ExerciseBase.DoesNotExist:
+ self.stdout.write(' Remote exercise base not found in local DB, skipping...')
+ continue
+
+ try:
+ video = ExerciseVideo.objects.get(uuid=video_uuid)
+ self.stdout.write(' Video already present locally, skipping...')
+ continue
+ except ExerciseVideo.DoesNotExist:
+ self.stdout.write(' Video not found in local DB, creating now...')
+ video = ExerciseVideo()
+ video.uuid = video_uuid
+ video.license_id = video_data['license']
+ video.license_author = video_data['license_author']
+
+ # Save the downloaded video
+ # http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-
+ retrieved_video = requests.get(video_data['video'], headers=headers)
+
+ # Temporary files on windows don't support the delete attribute
+ if os.name == 'nt':
+ img_temp = NamedTemporaryFile()
+ else:
+ img_temp = NamedTemporaryFile(delete=True)
+ img_temp.write(retrieved_video.content)
+ img_temp.flush()
+
+ video.exercise_base = exercise_base
+ video.is_main = video_data['is_main']
+ video.image.save(
+ os.path.basename(os.path.basename(video_data['image'])),
+ File(img_temp),
+ )
+ video.save()
+ self.stdout.write(self.style.SUCCESS(' successfully saved'))
+
+ if result['next']:
+ page += 1
+ result = requests.get(result['next'], headers=headers).json()
+ else:
+ all_videos_processed = True
diff --git a/wger/exercises/migrations/0015_exercise_videos.py b/wger/exercises/migrations/0015_exercise_videos.py
index f4b8ac00b..478124198 100644
--- a/wger/exercises/migrations/0015_exercise_videos.py
+++ b/wger/exercises/migrations/0015_exercise_videos.py
@@ -1,4 +1,4 @@
-# Generated by Django 3.2.10 on 2022-01-20 21:27
+# Generated by Django 3.2.10 on 2022-01-22 14:18
from django.db import migrations, models
import django.db.models.deletion
@@ -17,18 +17,87 @@ class Migration(migrations.Migration):
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),
+ 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')),
+ (
+ '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')),
+ (
+ 'video',
+ models.FileField(
+ upload_to=wger.exercises.models.video.exercise_video_upload_dir,
+ validators=[wger.exercises.models.video.validate_video],
+ verbose_name='Video'
+ )
+ ),
+ ('size', models.IntegerField(default=0, editable=False, verbose_name='Size')),
+ (
+ 'duration',
+ models.DecimalField(
+ decimal_places=2,
+ default=0,
+ editable=False,
+ max_digits=12,
+ verbose_name='Duration'
+ )
+ ),
+ ('width', models.IntegerField(default=0, editable=False, verbose_name='Width')),
+ ('height', models.IntegerField(default=0, editable=False, verbose_name='Height')),
+ (
+ 'codec',
+ models.CharField(
+ default='', editable=False, max_length=30, verbose_name='Codec'
+ )
+ ),
+ (
+ 'codec_long',
+ models.CharField(
+ default='', editable=False, max_length=100, verbose_name='Codec, long name'
+ )
+ ),
+ (
+ '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/video.py b/wger/exercises/models/video.py
index 8da780fb7..d6b919097 100644
--- a/wger/exercises/models/video.py
+++ b/wger/exercises/models/video.py
@@ -19,14 +19,37 @@ import pathlib
import uuid
# Django
+from django.core.exceptions import ValidationError
from django.db import models
+from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _
+# Third Party
+import ffmpeg
+
# wger
from wger.exercises.models import ExerciseBase
from wger.utils.models import AbstractLicenseModel
+def validate_video(value):
+
+ if value.size > 1024 * 1024 * 100:
+ raise ValidationError(_('Maximum file size is 100MB.'))
+
+ if value.file.content_type not in ['video/mp4', 'video/webm', 'video/ogg']:
+ raise ValidationError(_('File type not supported.'))
+
+ # If ffmpeg can't read the file, it will raise an exception
+ if not hasattr(value.file, 'temporary_file_path'):
+ raise ValidationError(_('File type not supported.'))
+
+ try:
+ ffmpeg.probe(value.file.temporary_file_path())
+ except ffmpeg.Error as e:
+ raise ValidationError(_('File is not a valid video.'))
+
+
def exercise_video_upload_dir(instance, filename):
"""
Returns the upload target for exercise videos
@@ -54,17 +77,38 @@ class ExerciseVideo(AbstractLicenseModel, models.Model):
)
"""The exercise the image belongs to"""
+ is_main = models.BooleanField(
+ verbose_name=_('Main video'),
+ default=False,
+ )
+ """A flag indicating whether the video is the exercise's main one"""
+
video = models.FileField(
- verbose_name=_('Video'),
- upload_to=exercise_video_upload_dir,
+ verbose_name=_('Video'), upload_to=exercise_video_upload_dir, validators=[validate_video]
)
"""Uploaded video"""
- is_main = models.BooleanField(
- verbose_name=_('Main video'),
- default=False,
+ size = models.IntegerField(verbose_name=_('Size'), default=0, editable=False)
+ """The video filesize, in bytes"""
+
+ duration = models.DecimalField(
+ verbose_name=_('Duration'), default=0, editable=False, max_digits=12, decimal_places=2
)
- """A flag indicating whether the image is the exercise's main image"""
+ """The video duration, in seconds"""
+
+ width = models.IntegerField(verbose_name=_('Width'), default=0, editable=False)
+ """The video width, in pixels"""
+
+ height = models.IntegerField(verbose_name=_('Height'), default=0, editable=False)
+ """The video height, in pixels"""
+
+ codec = models.CharField(verbose_name=_('Codec'), max_length=30, default='', editable=False)
+ """The video codec"""
+
+ codec_long = models.CharField(
+ verbose_name=_('Codec, long name'), max_length=100, default='', editable=False
+ )
+ """The video codec, in full"""
class Meta:
"""
@@ -74,6 +118,42 @@ class ExerciseVideo(AbstractLicenseModel, models.Model):
def get_owner_object(self):
"""
- Image has no owner information
+ Video has no owner information
"""
return False
+
+ def save(self, *args, **kwargs):
+ """
+ Save metadata about the video
+ """
+ if not self.pk:
+ probe_result = ffmpeg.probe(self.video.file.temporary_file_path())
+ self.size = probe_result['format']['size']
+ self.duration = probe_result['format']['duration']
+
+ # Streams are stored in a list, and we don't know which one is the video stream
+ for stream in probe_result['streams']:
+
+ if stream['codec_type'] != 'video':
+ continue
+
+ # Read out video information
+ self.width = stream['width']
+ self.height = stream['height']
+ self.codec = stream['codec_name']
+ self.codec_long = stream['codec_long_name']
+
+ super(ExerciseVideo, self).save(*args, **kwargs)
+
+
+@receiver(models.signals.post_delete, sender=ExerciseVideo)
+def auto_delete_file_on_delete(sender, instance: ExerciseVideo, **kwargs):
+ """
+ Deletes file from filesystem
+ when corresponding `MediaFile` object is deleted.
+ """
+ if instance.video:
+
+ path = pathlib.Path(instance.video.path)
+ if path.exists():
+ path.unlink()
diff --git a/wger/exercises/templates/exercise/view.html b/wger/exercises/templates/exercise/view.html
index d62f0b2de..f8509f494 100644
--- a/wger/exercises/templates/exercise/view.html
+++ b/wger/exercises/templates/exercise/view.html
@@ -144,13 +144,42 @@ $(document).ready(function() {
{# Videos #}
{% with videos=exercise.videos.all %}
-{% if videos or perms.exercises.change_exercisevideos %}
+{% if videos or perms.exercises.change_exercisevideo %}
+ <h5 class="mt-4">{% translate "Videos" %}</h5>
+ <div class="row row-cols-1 row-cols-md-2">
{% 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>
+ <div class="col mb-4">
+ <div class="card h-100">
+ <video controls preload="metadata" class="card-img-top">
+ <source src='{{ MEDIA_URL }}{{ video.video }}' type='video/mp4'>
+ Your browser does not support the video tag.
+ </video>
+ <div class="card-body text-center">
+ {% if perms.exercises.change_exercisevideo %}
+ <a href="{% url 'exercise:video:delete' exercise.pk video.pk %}" class="wger-modal-dialog btn btn-link">
+ <span class="{% fa_class 'trash' %}"></span>
+ </a>
+ <a href="{% url 'exercise:video:edit' video.pk %}" class="btn btn-link">
+ <span class="{% fa_class 'edit' %}"></span>
+ </a>
+ {% endif %}
+
+ {% if video.is_main %}
+ <p class="card-text text-wger-green">
+ <span class="{% fa_class 'medal' %}"></span>
+ </p>
+ {% endif %}
+ </div>
+ <div class="card-footer">
+ {{video.get_license_display}}
+ {% if video.license_author %}
+ {{video.license_author}}
+ {% endif %}
+ </div>
+ </div>
+ </div>
{% endfor %}
+ </div>
{% if perms.exercises.change_exercisevideo %}
<p>
diff --git a/wger/exercises/urls.py b/wger/exercises/urls.py
index b972b94f5..eae0afd4f 100644
--- a/wger/exercises/urls.py
+++ b/wger/exercises/urls.py
@@ -106,7 +106,7 @@ patterns_videos = [
name='edit',
),
path(
- '<int:exercise_pk>/image/<int:pk>/delete',
+ '<int:exercise_pk>/video/<int:pk>/delete',
videos.ExerciseVideoDeleteView.as_view(),
name='delete',
),