Skip to content

Commit 5271e4b

Browse files
committed
fix: YouTube preview falls back to OEmbed on poor scrape
When OG scrape returns empty title or no image (common with youtu.be short URLs), fall through to the YouTube OEmbed endpoint which reliably returns title, thumbnail, and embed HTML. Also cache successful results from all special preview handlers (YouTube, Reddit, Twitter, Flickr) which were previously only written to the response without being stored.
1 parent 9ce9941 commit 5271e4b

2 files changed

Lines changed: 10 additions & 4 deletions

File tree

internal/handler/preview.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,13 +134,13 @@ func (h *Handler) OGPreviewHandler(w http.ResponseWriter, r *http.Request) {
134134
if strings.Contains(urlParam, "reddit.com") {
135135
meta, err := h.GetRedditPreview(urlParam)
136136
if err == nil && len(meta) > 0 {
137-
json.NewEncoder(w).Encode(meta)
137+
h.cacheAndRespond(w, r, urlParam, meta)
138138
return
139139
}
140140
} else if strings.Contains(urlParam, "twitter.com") || strings.Contains(urlParam, "x.com") {
141141
meta, err := h.GetTwitterPreview(urlParam)
142142
if err == nil {
143-
json.NewEncoder(w).Encode(meta)
143+
h.cacheAndRespond(w, r, urlParam, meta)
144144
return
145145
}
146146
// If OEmbed returned ANY error (404, 403, etc.), we trust it. Do not fall back to scrape.
@@ -159,14 +159,14 @@ func (h *Handler) OGPreviewHandler(w http.ResponseWriter, r *http.Request) {
159159
} else if strings.Contains(urlParam, "flickr.com") {
160160
meta, err := h.GetFlickrPreview(urlParam)
161161
if err == nil {
162-
json.NewEncoder(w).Encode(meta)
162+
h.cacheAndRespond(w, r, urlParam, meta)
163163
return
164164
}
165165
// If not a single photo, fall through to normal OEmbed
166166
} else if strings.Contains(urlParam, "youtube.com") || strings.Contains(urlParam, "youtu.be") {
167167
meta, err := h.GetYouTubePreview(urlParam)
168168
if err == nil {
169-
json.NewEncoder(w).Encode(meta)
169+
h.cacheAndRespond(w, r, urlParam, meta)
170170
return
171171
}
172172
// If we detected a soft 404, stop here and return 404 so UI can render "missing" badge

internal/handler/preview_youtube.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ func (h *Handler) GetYouTubePreview(targetURL string) (map[string]string, error)
3434
title = strings.TrimSuffix(title, " - YouTube")
3535
meta["title"] = title
3636

37+
// If scrape yielded no real title or image, fall through to OEmbed
38+
// which is more reliable for YouTube
39+
if title == "" || meta["image"] == "" {
40+
return nil, fmt.Errorf("incomplete scrape, falling back to oembed")
41+
}
42+
3743
meta["type"] = "video"
3844

3945
return meta, nil

0 commit comments

Comments
 (0)