style: Enhance tutorial video management with URL normalization and improved preview functionality
This commit is contained in:
+91
-8
@@ -13,6 +13,7 @@ import threading
|
||||
from datetime import timedelta, datetime, date
|
||||
from functools import wraps
|
||||
from io import BytesIO
|
||||
from urllib.parse import parse_qs, quote, urlparse
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
from werkzeug.utils import secure_filename
|
||||
import bleach
|
||||
@@ -36,7 +37,8 @@ def set_security_headers(response):
|
||||
response.headers["X-Frame-Options"] = "SAMEORIGIN"
|
||||
response.headers["X-XSS-Protection"] = "1; mode=block"
|
||||
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
|
||||
response.headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com https://fonts.googleapis.com; img-src 'self' data:; connect-src 'self';"
|
||||
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
|
||||
response.headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com https://fonts.googleapis.com; img-src 'self' data:; connect-src 'self'; frame-src 'self' https://www.youtube.com https://youtube.com https://www.youtube-nocookie.com https://youtube-nocookie.com; media-src 'self' https:;"
|
||||
return response
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
@@ -186,6 +188,50 @@ def _sanitize_text(text: str, max_length: int = 255) -> str:
|
||||
return text
|
||||
|
||||
|
||||
def _normalize_tutorial_video_url(url: str, origin: str = "") -> str:
|
||||
"""Normalize user-provided tutorial URLs to safe embed URLs where possible."""
|
||||
raw = _sanitize_text(url, 800)
|
||||
if not raw:
|
||||
return ""
|
||||
|
||||
if raw.startswith("/"):
|
||||
return raw
|
||||
|
||||
try:
|
||||
parsed = urlparse(raw)
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
host = (parsed.netloc or "").lower()
|
||||
path = parsed.path or ""
|
||||
video_id = ""
|
||||
|
||||
if host in {"youtu.be", "www.youtu.be"}:
|
||||
video_id = path.strip("/").split("/")[0]
|
||||
elif "youtube.com" in host:
|
||||
if path.startswith("/watch"):
|
||||
video_id = (parse_qs(parsed.query).get("v") or [""])[0]
|
||||
elif path.startswith("/embed/"):
|
||||
video_id = path.split("/embed/", 1)[1].split("/")[0]
|
||||
elif path.startswith("/shorts/"):
|
||||
video_id = path.split("/shorts/", 1)[1].split("/")[0]
|
||||
elif "youtube-nocookie.com" in host and path.startswith("/embed/"):
|
||||
video_id = path.split("/embed/", 1)[1].split("/")[0]
|
||||
|
||||
if video_id and re.fullmatch(r"[A-Za-z0-9_-]{6,20}", video_id):
|
||||
origin_value = quote((origin or "").rstrip("/"), safe=":/")
|
||||
if origin_value:
|
||||
return (
|
||||
f"https://www.youtube-nocookie.com/embed/{video_id}"
|
||||
f"?rel=0&modestbranding=1&playsinline=1&origin={origin_value}"
|
||||
)
|
||||
return f"https://www.youtube-nocookie.com/embed/{video_id}?rel=0&modestbranding=1&playsinline=1"
|
||||
|
||||
if parsed.scheme in {"http", "https"} and host:
|
||||
return raw
|
||||
return ""
|
||||
|
||||
|
||||
def _slugify_subdomain(value: str) -> str:
|
||||
cleaned = (value or "").strip().lower()
|
||||
cleaned = cleaned.replace("ä", "ae").replace("ö", "oe").replace("ü", "ue").replace("ß", "ss")
|
||||
@@ -2399,9 +2445,24 @@ def my_instance_management():
|
||||
def my_tutorials():
|
||||
"""Display tutorial videos for the logged-in user."""
|
||||
client = None
|
||||
origin = request.url_root.rstrip("/")
|
||||
try:
|
||||
client, col = _get_collection("tutorials")
|
||||
tutorials = list(col.find({"published": True}, {"_id": 1, "title": 1, "description": 1, "video_url": 1, "thumbnail_url": 1, "duration": 1, "category": 1, "created_at": 1}).sort("created_at", -1))
|
||||
tutorials = list(
|
||||
col.find(
|
||||
{"published": True},
|
||||
{
|
||||
"_id": 1,
|
||||
"title": 1,
|
||||
"description": 1,
|
||||
"video_url": 1,
|
||||
"thumbnail_url": 1,
|
||||
"duration": 1,
|
||||
"category": 1,
|
||||
"created_at": 1,
|
||||
},
|
||||
).sort("created_at", -1)
|
||||
)
|
||||
except PyMongoError:
|
||||
flash("Tutorials konnten nicht geladen werden.", "error")
|
||||
tutorials = []
|
||||
@@ -2415,7 +2476,7 @@ def my_tutorials():
|
||||
"_id": "1",
|
||||
"title": "Erste Schritte mit Invario",
|
||||
"description": "Lernen Sie die Grundlagen von Invario und wie Sie Ihre erste Instanz einrichten.",
|
||||
"video_url": "https://www.youtube.com/embed/dQw4w9WgXcQ",
|
||||
"video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
|
||||
"thumbnail_url": "/static/images/tutorial-thumb-1.jpg",
|
||||
"duration": "12:34",
|
||||
"category": "Anfänger"
|
||||
@@ -2424,7 +2485,7 @@ def my_tutorials():
|
||||
"_id": "2",
|
||||
"title": "Inventarverwaltung",
|
||||
"description": "Alles über die Verwaltung Ihres Inventars und der Ausleihvorgänge.",
|
||||
"video_url": "https://www.youtube.com/embed/dQw4w9WgXcQ",
|
||||
"video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
|
||||
"thumbnail_url": "/static/images/tutorial-thumb-2.jpg",
|
||||
"duration": "18:45",
|
||||
"category": "Funktionen"
|
||||
@@ -2433,12 +2494,21 @@ def my_tutorials():
|
||||
"_id": "3",
|
||||
"title": "Admin-Funktionen",
|
||||
"description": "Erweiterte Administratorfunktionen und Systemverwaltung.",
|
||||
"video_url": "https://www.youtube.com/embed/dQw4w9WgXcQ",
|
||||
"video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
|
||||
"thumbnail_url": "/static/images/tutorial-thumb-3.jpg",
|
||||
"duration": "22:15",
|
||||
"category": "Admin"
|
||||
}
|
||||
]
|
||||
|
||||
normalized_tutorials = []
|
||||
for item in tutorials:
|
||||
normalized = dict(item)
|
||||
normalized["video_url"] = _normalize_tutorial_video_url(item.get("video_url") or "", origin)
|
||||
if normalized.get("video_url"):
|
||||
normalized_tutorials.append(normalized)
|
||||
|
||||
tutorials = normalized_tutorials
|
||||
|
||||
return render_template("my_tutorials.html", tutorials=tutorials)
|
||||
|
||||
@@ -2452,8 +2522,21 @@ def append_video():
|
||||
duration = _sanitize_text(request.form.get("duration") or "", 20)
|
||||
category = _sanitize_text(request.form.get("category") or "", 50)
|
||||
|
||||
if not title or not video_url:
|
||||
flash("Bitte Titel und Video-URL angeben.", "error")
|
||||
if not title:
|
||||
flash("Bitte einen Titel für das Tutorial eingeben.", "error")
|
||||
return redirect(url_for("admin_blog"))
|
||||
|
||||
if not video_url:
|
||||
flash("Bitte eine Video-URL eingeben.", "error")
|
||||
return redirect(url_for("admin_blog"))
|
||||
|
||||
normalized_video_url = _normalize_tutorial_video_url(video_url, request.url_root.rstrip("/"))
|
||||
|
||||
if not normalized_video_url:
|
||||
flash(
|
||||
"Ungültige Video-URL. Erlaubt sind YouTube-Links im Format watch?v=..., youtu.be/..., shorts/... oder embed/...",
|
||||
"error",
|
||||
)
|
||||
return redirect(url_for("admin_blog"))
|
||||
|
||||
client = None
|
||||
@@ -2463,7 +2546,7 @@ def append_video():
|
||||
{
|
||||
"title": title,
|
||||
"description": description,
|
||||
"video_url": video_url,
|
||||
"video_url": normalized_video_url,
|
||||
"thumbnail_url": thumbnail_url,
|
||||
"duration": duration,
|
||||
"category": category,
|
||||
|
||||
Reference in New Issue
Block a user