mirror of
https://github.com/truewhile/MeBox.git
synced 2026-10-07 13:56: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 {
|
func imageProxyHandler(svc *service.Container) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
raw := c.Query("url")
|
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
|
// Serve handles upstream errors internally by returning a 1×1 PNG
|
||||||
// placeholder, so the only error we can get back here is a malformed
|
// 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.
|
// 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
|
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
|
// Serve writes the requested image to w. Caller is expected to validate
|
||||||
// the JWT before invoking it.
|
// the JWT before invoking it.
|
||||||
func (p *ImageProxy) Serve(ctx context.Context, w http.ResponseWriter, r *http.Request, raw string) error {
|
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) {
|
func TestImageProxyCachesCloudResolvedImage(t *testing.T) {
|
||||||
var calls int32
|
var calls int32
|
||||||
proxy := NewImageProxy(&config.Config{Cache: config.CacheConfig{CacheDir: filepath.Join(t.TempDir(), "cache")}}, zap.NewNop())
|
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
|
// 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.
|
// 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 ''
|
if (!remote) return ''
|
||||||
const versionQuery = version ? `v=${encodeURIComponent(version)}` : ''
|
const versionQuery = version ? `v=${encodeURIComponent(version)}` : ''
|
||||||
if (remote.startsWith('/api/img')) return withQuery(withoutAuthQuery(remote), versionQuery)
|
const retryQuery = retryFailed ? 'retry=1' : ''
|
||||||
if (remote.startsWith('/api/cloud/play/')) return withQuery(withoutAuthQuery(remote), versionQuery)
|
const imageQuery = [versionQuery, retryQuery].filter(Boolean).join('&')
|
||||||
if (remote.startsWith('/api/')) return withQuery(withQuery(remote, tokenQuery()), versionQuery)
|
if (remote.startsWith('/api/img')) return withQuery(withoutAuthQuery(remote), imageQuery)
|
||||||
return withQuery(`/api/img?url=${encodeURIComponent(remote)}`, versionQuery)
|
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 {
|
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 type { DiscoverItem } from '../api/discover'
|
||||||
import { imageURL } from '../api/client'
|
import { imageURL } from '../api/client'
|
||||||
@@ -7,10 +8,12 @@ import { discoverItemSource } from './discoverPageModel'
|
|||||||
export function ContentRow({
|
export function ContentRow({
|
||||||
title,
|
title,
|
||||||
items,
|
items,
|
||||||
|
imageVersion,
|
||||||
onSelect,
|
onSelect,
|
||||||
}: {
|
}: {
|
||||||
title: string
|
title: string
|
||||||
items: DiscoverItem[]
|
items: DiscoverItem[]
|
||||||
|
imageVersion?: string
|
||||||
onSelect: (item: DiscoverItem) => void
|
onSelect: (item: DiscoverItem) => void
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
@@ -18,7 +21,7 @@ export function ContentRow({
|
|||||||
<h2 className="pl-1 font-display text-2xl font-semibold text-ink-600">{title}</h2>
|
<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">
|
<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) => (
|
{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>
|
</div>
|
||||||
</section>
|
</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 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 (
|
return (
|
||||||
<button
|
<button
|
||||||
type="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"
|
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">
|
<div className="relative aspect-[2/3] w-full overflow-hidden bg-surface-900">
|
||||||
{item.poster_url ? (
|
{posterSrc && (
|
||||||
<img
|
<img
|
||||||
src={imageURL(item.poster_url)}
|
src={posterSrc}
|
||||||
alt={item.title}
|
alt={item.title}
|
||||||
loading="lazy"
|
loading="lazy"
|
||||||
referrerPolicy="no-referrer"
|
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>
|
||||||
)}
|
)}
|
||||||
<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">
|
<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 { 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 { discoverAPI, type DiscoverItem, type DiscoverSection } from '../api/discover'
|
||||||
import { ContentRow, DiscoverSkeleton } from './DiscoverContentRow'
|
import { ContentRow, DiscoverSkeleton } from './DiscoverContentRow'
|
||||||
@@ -19,6 +19,8 @@ export function DiscoverPage() {
|
|||||||
const [sectionsReady, setSectionsReady] = useState(false)
|
const [sectionsReady, setSectionsReady] = useState(false)
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const [activeItem, setActiveItem] = useState<DiscoverItem | null>(null)
|
const [activeItem, setActiveItem] = useState<DiscoverItem | null>(null)
|
||||||
|
const [reloadSeq, setReloadSeq] = useState(0)
|
||||||
|
const [imageVersion, setImageVersion] = useState(() => String(Date.now()))
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
@@ -101,7 +103,7 @@ export function DiscoverPage() {
|
|||||||
return () => {
|
return () => {
|
||||||
cancelled = true
|
cancelled = true
|
||||||
}
|
}
|
||||||
}, [sections, sectionsReady, selected])
|
}, [sections, sectionsReady, selected, reloadSeq])
|
||||||
|
|
||||||
const sectionMap = useMemo(
|
const sectionMap = useMemo(
|
||||||
() => new Map(sections.map((section) => [section.key, section])),
|
() => 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 (
|
return (
|
||||||
<div className="mx-auto max-w-7xl space-y-8 px-4 py-6">
|
<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">
|
<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>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-col gap-3 lg:items-end">
|
||||||
{sections.map((section) => {
|
<button
|
||||||
const active = selected.includes(section.key)
|
type="button"
|
||||||
return (
|
onClick={refreshDiscover}
|
||||||
<button
|
disabled={!sectionsReady || selected.length === 0}
|
||||||
key={section.key}
|
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"
|
||||||
type="button"
|
>
|
||||||
onClick={() => toggleSection(section.key)}
|
<RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
|
||||||
className={
|
刷新
|
||||||
'rounded-full border px-3 py-1.5 text-xs font-semibold transition ' +
|
</button>
|
||||||
(active
|
<div className="flex flex-wrap justify-start gap-2 lg:justify-end">
|
||||||
? 'border-primary-400 bg-primary-400/15 text-brand-500'
|
{sections.map((section) => {
|
||||||
: 'border-gray-200 bg-white text-gray-500 hover:border-primary-300 hover:text-ink-600')
|
const active = selected.includes(section.key)
|
||||||
}
|
return (
|
||||||
>
|
<button
|
||||||
{section.label}
|
key={section.key}
|
||||||
</button>
|
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>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -181,6 +199,7 @@ export function DiscoverPage() {
|
|||||||
key={key}
|
key={key}
|
||||||
title={sectionMap.get(key)?.label ?? key}
|
title={sectionMap.get(key)?.label ?? key}
|
||||||
items={items}
|
items={items}
|
||||||
|
imageVersion={imageVersion}
|
||||||
onSelect={setActiveItem}
|
onSelect={setActiveItem}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user