mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-29 03:26:37 +08:00
fix: retry failed discover artwork
This commit is contained in:
@@ -70,6 +70,9 @@ func stopTranscodeHandler(svc *service.Container) gin.HandlerFunc {
|
||||
func imageProxyHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
raw := c.Query("url")
|
||||
if c.Query("retry") != "" || c.Query("refresh") != "" {
|
||||
_ = svc.ImageProxy.RemoveFailed(raw)
|
||||
}
|
||||
// Serve handles upstream errors internally by returning a 1×1 PNG
|
||||
// placeholder, so the only error we can get back here is a malformed
|
||||
// URL. In that case we still return 400 to make the misuse visible.
|
||||
|
||||
@@ -38,6 +38,20 @@ func (p *ImageProxy) RemoveCached(raw string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *ImageProxy) RemoveFailed(raw string) error {
|
||||
if !isHTTPish(raw) {
|
||||
return nil
|
||||
}
|
||||
_, _, failPath, err := p.remoteImageCachePaths(raw)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if err := os.Remove(failPath); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Serve writes the requested image to w. Caller is expected to validate
|
||||
// the JWT before invoking it.
|
||||
func (p *ImageProxy) Serve(ctx context.Context, w http.ResponseWriter, r *http.Request, raw string) error {
|
||||
|
||||
@@ -132,6 +132,52 @@ func TestImageProxyCachesFailedRemoteImageFetch(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageProxyRemoveFailedAllowsRetry(t *testing.T) {
|
||||
var calls int32
|
||||
proxy := NewImageProxy(&config.Config{Cache: config.CacheConfig{CacheDir: filepath.Join(t.TempDir(), "cache")}}, zap.NewNop())
|
||||
proxy.client = &http.Client{Transport: imageRoundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
call := atomic.AddInt32(&calls, 1)
|
||||
if call == 1 {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusBadGateway,
|
||||
Status: "502 Bad Gateway",
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader("upstream unavailable")),
|
||||
Request: req,
|
||||
}, nil
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Status: "200 OK",
|
||||
Header: http.Header{"Content-Type": []string{"image/jpeg"}},
|
||||
Body: io.NopCloser(strings.NewReader("poster-bytes")),
|
||||
Request: req,
|
||||
}, nil
|
||||
})}
|
||||
|
||||
raw := "https://image.tmdb.org/t/p/w500/retry-poster.jpg"
|
||||
rec := httptest.NewRecorder()
|
||||
if err := proxy.Serve(t.Context(), rec, httptest.NewRequest(http.MethodGet, "/api/img", nil), raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec.Body.Len() != len(transparent1x1PNG) {
|
||||
t.Fatalf("first body length = %d, want placeholder %d", rec.Body.Len(), len(transparent1x1PNG))
|
||||
}
|
||||
if err := proxy.RemoveFailed(raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
if err := proxy.Serve(t.Context(), rec, httptest.NewRequest(http.MethodGet, "/api/img?v=retry", nil), raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := rec.Body.String(); got != "poster-bytes" {
|
||||
t.Fatalf("retried body = %q, want poster bytes", got)
|
||||
}
|
||||
if got := atomic.LoadInt32(&calls); got != 2 {
|
||||
t.Fatalf("upstream calls = %d, want 2 after retry", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageProxyCachesCloudResolvedImage(t *testing.T) {
|
||||
var calls int32
|
||||
proxy := NewImageProxy(&config.Config{Cache: config.CacheConfig{CacheDir: filepath.Join(t.TempDir(), "cache")}}, zap.NewNop())
|
||||
|
||||
@@ -151,13 +151,15 @@ export function hlsURL(mediaId: string): string {
|
||||
|
||||
// imageURL converts a remote poster URL into a same-origin proxy URL so it
|
||||
// can never be blocked by CORS / GFW. Empty strings pass through unchanged.
|
||||
export function imageURL(remote?: string, version?: string): string {
|
||||
export function imageURL(remote?: string, version?: string, retryFailed = false): string {
|
||||
if (!remote) return ''
|
||||
const versionQuery = version ? `v=${encodeURIComponent(version)}` : ''
|
||||
if (remote.startsWith('/api/img')) return withQuery(withoutAuthQuery(remote), versionQuery)
|
||||
if (remote.startsWith('/api/cloud/play/')) return withQuery(withoutAuthQuery(remote), versionQuery)
|
||||
if (remote.startsWith('/api/')) return withQuery(withQuery(remote, tokenQuery()), versionQuery)
|
||||
return withQuery(`/api/img?url=${encodeURIComponent(remote)}`, versionQuery)
|
||||
const retryQuery = retryFailed ? 'retry=1' : ''
|
||||
const imageQuery = [versionQuery, retryQuery].filter(Boolean).join('&')
|
||||
if (remote.startsWith('/api/img')) return withQuery(withoutAuthQuery(remote), imageQuery)
|
||||
if (remote.startsWith('/api/cloud/play/')) return withQuery(withoutAuthQuery(remote), imageQuery)
|
||||
if (remote.startsWith('/api/')) return withQuery(withQuery(remote, tokenQuery()), imageQuery)
|
||||
return withQuery(`/api/img?url=${encodeURIComponent(remote)}`, imageQuery)
|
||||
}
|
||||
|
||||
function withQuery(url: string, query: string): string {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Info } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { ImageOff, Info } from 'lucide-react'
|
||||
|
||||
import type { DiscoverItem } from '../api/discover'
|
||||
import { imageURL } from '../api/client'
|
||||
@@ -7,10 +8,12 @@ import { discoverItemSource } from './discoverPageModel'
|
||||
export function ContentRow({
|
||||
title,
|
||||
items,
|
||||
imageVersion,
|
||||
onSelect,
|
||||
}: {
|
||||
title: string
|
||||
items: DiscoverItem[]
|
||||
imageVersion?: string
|
||||
onSelect: (item: DiscoverItem) => void
|
||||
}) {
|
||||
return (
|
||||
@@ -18,7 +21,7 @@ export function ContentRow({
|
||||
<h2 className="pl-1 font-display text-2xl font-semibold text-ink-600">{title}</h2>
|
||||
<div className="grid grid-cols-3 gap-4 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-7 xl:grid-cols-8">
|
||||
{items.map((item, index) => (
|
||||
<DiscoverCard key={discoverKey(item, index)} item={item} onSelect={onSelect} />
|
||||
<DiscoverCard key={discoverKey(item, index)} item={item} imageVersion={imageVersion} onSelect={onSelect} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
@@ -42,8 +45,28 @@ export function DiscoverSkeleton() {
|
||||
)
|
||||
}
|
||||
|
||||
function DiscoverCard({ item, onSelect }: { item: DiscoverItem; onSelect: (item: DiscoverItem) => void }) {
|
||||
function DiscoverCard({
|
||||
item,
|
||||
imageVersion,
|
||||
onSelect,
|
||||
}: {
|
||||
item: DiscoverItem
|
||||
imageVersion?: string
|
||||
onSelect: (item: DiscoverItem) => void
|
||||
}) {
|
||||
const source = discoverItemSource(item)
|
||||
const [posterFailed, setPosterFailed] = useState(false)
|
||||
const posterSrc = useMemo(
|
||||
() => imageURL(item.poster_url, imageVersion, true),
|
||||
[imageVersion, item.poster_url],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
setPosterFailed(false)
|
||||
}, [posterSrc])
|
||||
|
||||
const showFallback = !posterSrc || posterFailed
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
@@ -51,17 +74,28 @@ function DiscoverCard({ item, onSelect }: { item: DiscoverItem; onSelect: (item:
|
||||
className="group relative overflow-hidden rounded-xl border border-gray-200 bg-gray-50 text-left transition-all duration-300 hover:-translate-y-1 hover:border-primary-500/30 hover:shadow-xl focus:outline-none focus:ring-2 focus:ring-primary-400/40"
|
||||
>
|
||||
<div className="relative aspect-[2/3] w-full overflow-hidden bg-surface-900">
|
||||
{item.poster_url ? (
|
||||
{posterSrc && (
|
||||
<img
|
||||
src={imageURL(item.poster_url)}
|
||||
src={posterSrc}
|
||||
alt={item.title}
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer"
|
||||
className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
|
||||
onError={() => setPosterFailed(true)}
|
||||
onLoad={(event) => {
|
||||
const img = event.currentTarget
|
||||
setPosterFailed(img.naturalWidth <= 1 && img.naturalHeight <= 1)
|
||||
}}
|
||||
className={
|
||||
'h-full w-full object-cover transition-transform duration-500 group-hover:scale-105 ' +
|
||||
(posterFailed ? 'opacity-0' : 'opacity-100')
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center text-xs text-gray-500">
|
||||
无海报
|
||||
)}
|
||||
{showFallback && (
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-gray-100 px-3 text-center text-gray-500">
|
||||
<ImageOff size={22} className="text-gray-400" />
|
||||
<span className="line-clamp-2 text-xs font-medium text-gray-600">{item.title}</span>
|
||||
<span className="text-[10px] text-gray-400">{posterSrc ? '海报待刷新' : '无海报'}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="absolute left-1.5 top-1.5 rounded-xl border border-white/20 bg-black/65 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-white backdrop-blur-sm">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { AlertTriangle, Sparkles } from 'lucide-react'
|
||||
import { AlertTriangle, RefreshCw, Sparkles } from 'lucide-react'
|
||||
|
||||
import { discoverAPI, type DiscoverItem, type DiscoverSection } from '../api/discover'
|
||||
import { ContentRow, DiscoverSkeleton } from './DiscoverContentRow'
|
||||
@@ -19,6 +19,8 @@ export function DiscoverPage() {
|
||||
const [sectionsReady, setSectionsReady] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [activeItem, setActiveItem] = useState<DiscoverItem | null>(null)
|
||||
const [reloadSeq, setReloadSeq] = useState(0)
|
||||
const [imageVersion, setImageVersion] = useState(() => String(Date.now()))
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
@@ -101,7 +103,7 @@ export function DiscoverPage() {
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [sections, sectionsReady, selected])
|
||||
}, [sections, sectionsReady, selected, reloadSeq])
|
||||
|
||||
const sectionMap = useMemo(
|
||||
() => new Map(sections.map((section) => [section.key, section])),
|
||||
@@ -119,6 +121,11 @@ export function DiscoverPage() {
|
||||
})
|
||||
}
|
||||
|
||||
const refreshDiscover = () => {
|
||||
setImageVersion(String(Date.now()))
|
||||
setReloadSeq((current) => current + 1)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl space-y-8 px-4 py-6">
|
||||
<header className="flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between">
|
||||
@@ -136,25 +143,36 @@ export function DiscoverPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{sections.map((section) => {
|
||||
const active = selected.includes(section.key)
|
||||
return (
|
||||
<button
|
||||
key={section.key}
|
||||
type="button"
|
||||
onClick={() => toggleSection(section.key)}
|
||||
className={
|
||||
'rounded-full border px-3 py-1.5 text-xs font-semibold transition ' +
|
||||
(active
|
||||
? 'border-primary-400 bg-primary-400/15 text-brand-500'
|
||||
: 'border-gray-200 bg-white text-gray-500 hover:border-primary-300 hover:text-ink-600')
|
||||
}
|
||||
>
|
||||
{section.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
<div className="flex flex-col gap-3 lg:items-end">
|
||||
<button
|
||||
type="button"
|
||||
onClick={refreshDiscover}
|
||||
disabled={!sectionsReady || selected.length === 0}
|
||||
className="inline-flex items-center justify-center gap-2 rounded-lg border border-gray-200 bg-white px-3 py-2 text-xs font-semibold text-ink-600 transition hover:border-primary-300 hover:text-brand-500 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
|
||||
刷新
|
||||
</button>
|
||||
<div className="flex flex-wrap justify-start gap-2 lg:justify-end">
|
||||
{sections.map((section) => {
|
||||
const active = selected.includes(section.key)
|
||||
return (
|
||||
<button
|
||||
key={section.key}
|
||||
type="button"
|
||||
onClick={() => toggleSection(section.key)}
|
||||
className={
|
||||
'rounded-full border px-3 py-1.5 text-xs font-semibold transition ' +
|
||||
(active
|
||||
? 'border-primary-400 bg-primary-400/15 text-brand-500'
|
||||
: 'border-gray-200 bg-white text-gray-500 hover:border-primary-300 hover:text-ink-600')
|
||||
}
|
||||
>
|
||||
{section.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -181,6 +199,7 @@ export function DiscoverPage() {
|
||||
key={key}
|
||||
title={sectionMap.get(key)?.label ?? key}
|
||||
items={items}
|
||||
imageVersion={imageVersion}
|
||||
onSelect={setActiveItem}
|
||||
/>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user