Aufteilung nach Zuständigkeit (httpapi, account, linkpreview, charts, impression, media, database, apperr), Abhängigkeiten per Konstruktor statt globalem Zustand, Worker mit Context-gesteuertem Lebenszyklus. Lange Funktionen aufgeteilt, ignorierte Fehler behandelt bzw. geloggt, Schema als schema.sql eingebettet. Logs jetzt strukturiert (slog) ohne Client-IP und Query-String. Tests laufen parallel mit eigenem Schema je Test; neue Tests für account, media und apperr. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TiXsPUqw7oeomZ8wZrQW5q
68 lines
1.8 KiB
Go
68 lines
1.8 KiB
Go
package linkpreview
|
|
|
|
import (
|
|
"net/url"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
const maxURLLen = 2048
|
|
|
|
// linkPattern findet Links wie linkify im Frontend (format.tsx), damit die
|
|
// Vorschau exakt zum ersten dort verlinkten Text gehört. \p{Z} und U+FEFF
|
|
// gleichen Gos ASCII-\s an das Unicode-\s von JavaScript an.
|
|
var linkPattern = regexp.MustCompile(`https?://[^\s\p{Z}\x{feff}<]+`)
|
|
|
|
var youtubeIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{11}$`)
|
|
|
|
// Key liefert die kanonische URL des ersten Links in content oder "".
|
|
// YouTube-Links aller Formen werden auf watch?v=<id> gebracht, damit dasselbe
|
|
// Video nur einmal geholt wird.
|
|
func Key(content string) string {
|
|
raw := linkPattern.FindString(content)
|
|
if raw == "" || len(raw) > maxURLLen {
|
|
return ""
|
|
}
|
|
u, err := url.Parse(raw)
|
|
if err != nil || u.Hostname() == "" {
|
|
return ""
|
|
}
|
|
if id := youtubeID(u); id != "" {
|
|
return youtubeWatchURL(id)
|
|
}
|
|
return raw
|
|
}
|
|
|
|
func youtubeWatchURL(id string) string { return "https://www.youtube.com/watch?v=" + id }
|
|
|
|
// youtubeID erkennt die Video-ID in watch?v=, youtu.be/, /shorts/, /live/,
|
|
// /embed/ und /v/ auf youtube.com, m./music./www.-Varianten und
|
|
// youtube-nocookie.com. "" für alles andere (Kanäle, Playlists, ...).
|
|
func youtubeID(u *url.URL) string {
|
|
host := strings.ToLower(u.Hostname())
|
|
for _, p := range []string{"www.", "m.", "music."} {
|
|
host = strings.TrimPrefix(host, p)
|
|
}
|
|
seg := strings.Split(strings.Trim(u.Path, "/"), "/")
|
|
var id string
|
|
switch host {
|
|
case "youtu.be":
|
|
id = seg[0]
|
|
case "youtube.com", "youtube-nocookie.com":
|
|
switch {
|
|
case u.Path == "/watch":
|
|
id = u.Query().Get("v")
|
|
case len(seg) >= 2 && isVideoPathPrefix(seg[0]):
|
|
id = seg[1]
|
|
}
|
|
}
|
|
if !youtubeIDPattern.MatchString(id) {
|
|
return ""
|
|
}
|
|
return id
|
|
}
|
|
|
|
func isVideoPathPrefix(s string) bool {
|
|
return s == "shorts" || s == "live" || s == "embed" || s == "v"
|
|
}
|