Skip to content

一分钟搭建影视站,支持Docker等部署方式

feat(图片加载): 新增 SmartImage 降级链组件并默认直连优先

bestZwei8bbeb7906d05
diff --git a/src/app/live/page.tsx b/src/app/live/page.tsx
index fcf1d62..a000cc5 100644
--- a/src/app/live/page.tsx
+++ b/src/app/live/page.tsx
@@ -21,7 +21,8 @@ import { LiveEpgPanel } from '@/components/live-epg-panel';
import { Spinner } from '@/components/states';
import { useAuth } from '@/components/auth';
import { allLiveSources, useAppStore } from '@/lib/store';
-import { buildImageUrl, cn } from '@/lib/utils';
+import { cn } from '@/lib/utils';
+import { SmartImage } from '@/components/smart-image';
/**
* 直播页:左侧播放器 + 频道信息 + 节目单;右侧频道侧栏。
@@ -51,6 +52,7 @@ function LiveContent() {
const [copied, setCopied] = useState(false);
// 移动端频道抽屉开合
const [listOpen, setListOpen] = useState(false);
+ const [logoFailed, setLogoFailed] = useState(false);
/** 侧栏上报的筛选排序结果(键盘换台沿此列表顺序);ref 存储,不触发重渲染 */
const filteredRef = useRef<LiveChannelItem[]>([]);
/** 当前频道镜像:selectChannel 内读取最近一次播放的频道,用于记录"上一个频道" */
@@ -112,6 +114,9 @@ function LiveContent() {
} as LiveChannelItem;
}, [channels, currentUrl, searchParams]);
+ useEffect(() => {
+ setLogoFailed(false);
+ }, [currentChannel?.url]);
useEffect(() => {
currentChannelRef.current = currentChannel;
}, [currentChannel]);
@@ -209,7 +214,7 @@ function LiveContent() {
);
}
- const logo = buildImageUrl(currentChannel?.logo, imageProxyMode, customImageProxy);
+ const logo = currentChannel?.logo;
const isFavorite = currentChannel ? liveFavorites.includes(currentChannel.url) : false;
return (
@@ -247,9 +252,15 @@ function LiveContent() {
{currentChannel && (
<div className="bg-surface-raised border border-line rounded-lg p-3 mt-3 flex items-center gap-3">
<div className="w-10 h-10 shrink-0 rounded bg-chip flex items-center justify-center overflow-hidden">
- {logo ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img src={logo} alt="" className="w-full h-full object-contain" />
+ {logo && !logoFailed ? (
+ <SmartImage
+ url={logo}
+ mode={imageProxyMode}
+ customProxy={customImageProxy}
+ alt=""
+ className="w-full h-full object-contain"
+ onExhausted={() => setLogoFailed(true)}
+ />
) : (
<span className="text-xs text-faint">{currentChannel.name.slice(0, 1)}</span>
)}
diff --git a/src/components/detail-modal.tsx b/src/components/detail-modal.tsx
index 26bb350..637b81f 100644
--- a/src/components/detail-modal.tsx
+++ b/src/components/detail-modal.tsx
@@ -4,7 +4,8 @@ import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/client-api';
import type { SearchResultItem, VideoDetail } from '@/lib/types';
-import { buildImageUrl, buildWatchUrl } from '@/lib/utils';
+import { buildWatchUrl } from '@/lib/utils';
+import { SmartImage } from './smart-image';
import { useAppStore, resolveSource } from '@/lib/store';
import { useToast } from './toast';
import { cn } from '@/lib/utils';
@@ -30,12 +31,11 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;
const [posterFailed, setPosterFailed] = useState(false);
const abortRef = useRef<AbortController | null>(null);
const panelRef = useRef<HTMLDivElement>(null);
- const poster = buildImageUrl(item?.pic, store.imageProxyMode, store.customImageProxy);
// 打开时把焦点移入弹窗、Tab 圈闭在弹窗内、关闭后归还焦点
useFocusTrap(Boolean(item), panelRef);
- useEffect(() => setPosterFailed(false), [poster]);
+ useEffect(() => setPosterFailed(false), [item?.pic, store.imageProxyMode, store.customImageProxy]);
// 弹窗打开期间锁定背景滚动
useEffect(() => {
@@ -161,13 +161,15 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;
{!loading && !error && detail && (
<>
<div className="flex flex-col sm:flex-row gap-4 mb-4">
- {poster && !posterFailed && (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src={poster}
+ {item?.pic && !posterFailed && (
+ <SmartImage
+ url={item.pic}
+ mode={store.imageProxyMode}
+ customProxy={store.customImageProxy}
alt={item.name}
className="w-24 sm:w-32 aspect-[2/3] object-cover rounded-lg bg-chip shrink-0 self-center sm:self-start"
- onError={() => setPosterFailed(true)}
+ loading="eager"
+ onExhausted={() => setPosterFailed(true)}
/>
)}
<div className="min-w-0 space-y-3">
diff --git a/src/components/history-panel.tsx b/src/components/history-panel.tsx
index 40b5353..28bbcca 100644
--- a/src/components/history-panel.tsx
+++ b/src/components/history-panel.tsx
@@ -7,6 +7,7 @@ import { Drawer } from './drawer';
import { ConfirmDialog } from './confirm-dialog';
import { EmptyState, LoadingState } from './states';
import { Icon } from './icon';
+import { SmartImage } from './smart-image';
import {
db,
clearAllHistory,
@@ -15,7 +16,7 @@ import {
MAX_HISTORY,
type HistoryEntry,
} from '@/lib/db';
-import { buildWatchUrl, buildImageUrl, cn, formatRelativeTime, formatTime } from '@/lib/utils';
+import { buildWatchUrl, cn, formatRelativeTime, formatTime } from '@/lib/utils';
import { useToast } from './toast';
import { resolveSource, useAppStore } from '@/lib/store';
@@ -143,7 +144,6 @@ function HistoryItem({ item }: { item: HistoryEntry }) {
const { toast } = useToast();
const [imgFailed, setImgFailed] = useState(false);
const source = resolveSource({ customAPIs, envSources }, item.sourceKey);
- const pic = buildImageUrl(item.pic, imageProxyMode, customImageProxy);
const hasPercent =
item.playbackPosition > 10 && item.duration > 0 && item.playbackPosition < item.duration * 0.95;
@@ -194,14 +194,14 @@ function HistoryItem({ item }: { item: HistoryEntry }) {
className="block bg-card hover:bg-hover rounded-lg p-3 pr-10 transition-colors"
>
<div className="flex items-center gap-3">
- {pic && !imgFailed ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src={pic}
+ {item.pic && !imgFailed ? (
+ <SmartImage
+ url={item.pic}
+ mode={imageProxyMode}
+ customProxy={customImageProxy}
alt=""
className="w-10 h-14 object-cover rounded bg-chip"
- loading="lazy"
- onError={() => setImgFailed(true)}
+ onExhausted={() => setImgFailed(true)}
/>
) : (
<div className="w-10 h-14 rounded bg-chip flex items-center justify-center shrink-0">
diff --git a/src/components/live-channel-list.tsx b/src/components/live-channel-list.tsx
index eccc8f6..9262739 100644
--- a/src/components/live-channel-list.tsx
+++ b/src/components/live-channel-list.tsx
@@ -2,7 +2,8 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
-import { buildImageUrl, cn } from '@/lib/utils';
+import { cn } from '@/lib/utils';
+import { SmartImage } from './smart-image';
import { useAppStore } from '@/lib/store';
import {
isSlowSource,
@@ -397,11 +398,9 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect, onFilt
cursor={cursor === vi.index}
isFav={favSet.has(filtered[vi.index].url)}
probe={probeResults.get(filtered[vi.index].url)}
- logoUrl={buildImageUrl(
- filtered[vi.index].logo,
- imageProxyMode,
- customImageProxy
- )}
+ logo={filtered[vi.index].logo}
+ imageProxyMode={imageProxyMode}
+ customProxy={customImageProxy}
onSelect={onSelect}
onRemoveRecent={view === 'recent' ? removeRecent : undefined}
/>
@@ -436,7 +435,9 @@ const ChannelRow = memo(function ChannelRow({
cursor,
isFav,
probe,
- logoUrl,
+ logo,
+ imageProxyMode,
+ customProxy,
onSelect,
onRemoveRecent,
}: {
@@ -445,11 +446,16 @@ const ChannelRow = memo(function ChannelRow({
cursor: boolean;
isFav: boolean;
probe?: ProbeResult;
- logoUrl?: string;
+ logo?: string;
+ imageProxyMode: 'direct' | 'proxy' | 'custom';
+ customProxy: string;
onSelect: (channel: LiveChannelItem) => void;
/** 仅最近视图传入:删除该条观看记录 */
onRemoveRecent?: (url: string) => void;
}) {
+ const [logoFailed, setLogoFailed] = useState(false);
+ // 虚拟列表会复用行实例:换台(logo 变化)时重置失败态,避免下一个频道误显首字母
+ useEffect(() => setLogoFailed(false), [logo]);
// H.265/HEVC:国内 IPTV 常见,测活通过但 Chromium 内核通常无法软解
const isHevc = Boolean(probe?.codec && /hvc1|hev1|hevc/i.test(probe.codec));
// 源限速:分片可达但吞吐不足,绿点却播不了的主因
@@ -499,16 +505,14 @@ const ChannelRow = memo(function ChannelRow({
/>
{/* 台标 */}
<div className="w-7 h-7 shrink-0 rounded bg-chip flex items-center justify-center overflow-hidden">
- {logoUrl ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src={logoUrl}
+ {logo && !logoFailed ? (
+ <SmartImage
+ url={logo}
+ mode={imageProxyMode}
+ customProxy={customProxy}
alt=""
className="w-full h-full object-contain"
- loading="lazy"
- onError={(e) => {
- (e.target as HTMLImageElement).style.visibility = 'hidden';
- }}
+ onExhausted={() => setLogoFailed(true)}
/>
) : (
<span className="text-[10px] text-faint">{channel.name.slice(0, 1)}</span>
diff --git a/src/components/smart-image.tsx b/src/components/smart-image.tsx
new file mode 100644
index 0000000..8a420c8
--- /dev/null
+++ b/src/components/smart-image.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { buildImageCandidates } from '@/lib/utils';
+
+interface SmartImageProps {
+ /** 原始图片地址(未经代理加工,降级链由本组件按加载方式生成) */
+ url?: string;
+ mode: 'direct' | 'proxy' | 'custom';
+ customProxy?: string;
+ alt: string;
+ className?: string;
+ loading?: 'lazy' | 'eager';
+ /** 候选链耗尽后回调,调用方切换占位图等兜底 UI */
+ onExhausted?: () => void;
+}
+
+/**
+ * 带降级链的封面图组件:direct 模式按 buildImageCandidates 的顺序加载,
+ * onError 逐级回退(豆瓣图:直连 → 公共镜像 → 内置代理);
+ * 全部失败后触发 onExhausted 并停止渲染,由调用方展示占位图。
+ * referrerPolicy=no-referrer:不向图床暴露来源页,规避部分站点的 Referer 校验。
+ */
+export function SmartImage({
+ url,
+ mode,
+ customProxy = '',
+ alt,
+ className,
+ loading = 'lazy',
+ onExhausted,
+}: SmartImageProps) {
+ const candidates = buildImageCandidates(url, mode, customProxy);
+ const [idx, setIdx] = useState(0);
+
+ // 地址或加载方式变化时重置降级进度
+ useEffect(() => setIdx(0), [url, mode, customProxy]);
+ useEffect(() => {
+ if (idx >= candidates.length) onExhausted?.();
+ // 候选数组随 url/mode 变化,length 是充分的稳定信号
+ }, [idx, candidates.length, onExhausted]);
+
+ const src = candidates[idx];
+ if (!src) return null;
+ return (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={src}
+ alt={alt}
+ className={className}
+ loading={loading}
+ referrerPolicy="no-referrer"
+ onError={() => setIdx((i) => i + 1)}
+ />
+ );
+}
diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsx
index d1bdc8c..b1452c8 100644
--- a/src/components/source-manager.tsx
+++ b/src/components/source-manager.tsx
@@ -580,22 +580,28 @@ function PlaybackPanel() {
function ImagePanel() {
const store = useAppStore();
+ const mode = store.imageProxyMode;
+ const description: Record<'direct' | 'proxy' | 'custom', string> = {
+ direct: '原站直连;豆瓣封面自动换公共镜像,仍失败回退内置代理。最省服务器流量',
+ proxy: '所有封面经本站服务器转发并伪装来源,最稳定,消耗服务器流量',
+ custom: '使用你填写的模板转发封面图',
+ };
return (
<section>
<SectionTitle title="封面图加载" />
<div className="space-y-2">
<SelectRow
label="加载方式"
- value={store.imageProxyMode}
+ value={mode}
onChange={(v) => store.updateSettings({ imageProxyMode: v as 'direct' | 'proxy' | 'custom' })}
options={[
- { value: 'direct', label: '直连' },
- { value: 'proxy', label: '内置代理(默认)' },
+ { value: 'direct', label: '直连优先(推荐)' },
+ { value: 'proxy', label: '内置代理' },
{ value: 'custom', label: '自定义代理' },
]}
/>
- {store.imageProxyMode === 'custom' && <CustomProxyInput />}
- <p className="text-xs text-faint">豆瓣封面在某些网络下直连会被拒绝,可切换为内置代理。</p>
+ {mode === 'custom' && <CustomProxyInput />}
+ <p className="text-xs text-faint">{description[mode]}。</p>
</div>
</section>
);
diff --git a/src/components/switch-source.tsx b/src/components/switch-source.tsx
index f2d8a52..d94df0c 100644
--- a/src/components/switch-source.tsx
+++ b/src/components/switch-source.tsx
@@ -4,10 +4,11 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/client-api';
import type { SourceConfig, SearchResultItem } from '@/lib/types';
-import { buildImageUrl, buildWatchUrl, cn } from '@/lib/utils';
+import { buildWatchUrl, cn } from '@/lib/utils';
import { useAppStore, resolveSource } from '@/lib/store';
import { useToast } from './toast';
import { Icon } from './icon';
+import { SmartImage } from './smart-image';
import { EmptyState, LoadingState } from './states';
import { useFocusTrap } from './use-focus-trap';
@@ -206,7 +207,7 @@ export function SwitchSourceModal({
{sorted.map((c) => {
const isCurrent = c.source.key === currentSourceKey && String(c.result.vodId) === String(currentVodId);
const cardKey = `${c.source.key}_${c.result.vodId}`;
- const img = buildImageUrl(c.result.pic, store.imageProxyMode, store.customImageProxy);
+ const img = c.result.pic;
const coverFailed = imgFailed[cardKey] ?? false;
return (
<button
@@ -217,13 +218,13 @@ export function SwitchSourceModal({
>
<div className="relative aspect-[2/3] bg-chip">
{img && !coverFailed ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src={img}
+ <SmartImage
+ url={c.result.pic}
+ mode={store.imageProxyMode}
+ customProxy={store.customImageProxy}
alt={c.result.name}
className="w-full h-full object-cover"
- loading="lazy"
- onError={() => setImgFailed((prev) => ({ ...prev, [cardKey]: true }))}
+ onExhausted={() => setImgFailed((prev) => ({ ...prev, [cardKey]: true }))}
/>
) : (
<div className="w-full h-full flex items-center justify-center text-faint">
diff --git a/src/components/video-card.tsx b/src/components/video-card.tsx
index 90ce59e..6efdf48 100644
--- a/src/components/video-card.tsx
+++ b/src/components/video-card.tsx
@@ -2,9 +2,9 @@
import { useEffect, useMemo, useState } from 'react';
import type { SearchResultItem } from '@/lib/types';
-import { buildImageUrl } from '@/lib/utils';
import { useAppStore } from '@/lib/store';
import { cn } from '@/lib/utils';
+import { SmartImage } from './smart-image';
// —— 跨源同名聚合 ——
@@ -75,9 +75,7 @@ export function AggregatedCard({
const customImageProxy = useAppStore((s) => s.customImageProxy);
const [imgFailed, setImgFailed] = useState(false);
const [expanded, setExpanded] = useState(false);
- const primary = buildImageUrl(group.pic, imageProxyMode, customImageProxy);
- useEffect(() => setImgFailed(false), [primary]);
- const showImg = primary && !imgFailed;
+ const showImg = !!group.pic && !imgFailed;
const multi = group.items.length > 1;
const adult = useMemo(() => group.items.some((i) => i.isAdult), [group.items]);
@@ -105,13 +103,13 @@ export function AggregatedCard({
>
{showImg ? (
<div className="relative flex-shrink-0 w-[105px] sm:w-[120px] aspect-[2/3] bg-chip">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img
- src={primary}
+ <SmartImage
+ url={group.pic}
+ mode={imageProxyMode}
+ customProxy={customImageProxy}
alt={group.name}
className="absolute inset-0 h-full w-full object-cover"
- loading="lazy"
- onError={() => setImgFailed(true)}
+ onExhausted={() => setImgFailed(true)}
/>
<div className="absolute inset-0 bg-gradient-to-r from-black/30 to-transparent" />
{multi && (
@@ -207,10 +205,7 @@ export function VideoCard({ item, onClick }: { item: SearchResultItem; onClick:
const imageProxyMode = useAppStore((s) => s.imageProxyMode);
const customImageProxy = useAppStore((s) => s.customImageProxy);
const [imgFailed, setImgFailed] = useState(false);
- const primary = buildImageUrl(item.pic, imageProxyMode, customImageProxy);
- // 加载方式变化时重置失败状态,允许新地址重试
- useEffect(() => setImgFailed(false), [primary]);
- const showImg = primary && !imgFailed;
+ const showImg = !!item.pic && !imgFailed;
return (
<div
@@ -229,13 +224,13 @@ export function VideoCard({ item, onClick }: { item: SearchResultItem; onClick:
<div className="flex h-full">
{showImg ? (
<div className="relative flex-shrink-0 w-[105px] sm:w-[120px] aspect-[2/3] bg-chip">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img
- src={primary}
+ <SmartImage
+ url={item.pic}
+ mode={imageProxyMode}
+ customProxy={customImageProxy}
alt={item.name}
className="h-full w-full object-cover"
- loading="lazy"
- onError={() => setImgFailed(true)}
+ onExhausted={() => setImgFailed(true)}
/>
<div className="absolute inset-0 bg-gradient-to-r from-black/30 to-transparent" />
</div>
@@ -272,8 +267,7 @@ export function DoubanCard({ item, onClick }: { item: { title: string; cover: st
const imageProxyMode = useAppStore((s) => s.imageProxyMode);
const customImageProxy = useAppStore((s) => s.customImageProxy);
const [imgFailed, setImgFailed] = useState(false);
- const primary = buildImageUrl(item.cover, imageProxyMode, customImageProxy);
- useEffect(() => setImgFailed(false), [primary]);
+ useEffect(() => setImgFailed(false), [item.cover]);
return (
<div
@@ -290,14 +284,14 @@ export function DoubanCard({ item, onClick }: { item: { title: string; cover: st
}}
>
<div className="relative aspect-[2/3] bg-chip">
- {primary && !imgFailed ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src={primary}
+ {item.cover && !imgFailed ? (
+ <SmartImage
+ url={item.cover}
+ mode={imageProxyMode}
+ customProxy={customImageProxy}
alt={item.title}
className="w-full h-full object-cover"
- loading="lazy"
- onError={() => setImgFailed(true)}
+ onExhausted={() => setImgFailed(true)}
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-chip">
diff --git a/src/lib/proxy-handlers.ts b/src/lib/proxy-handlers.ts
index 12a3cc8..cb9b23e 100644
--- a/src/lib/proxy-handlers.ts
+++ b/src/lib/proxy-handlers.ts
@@ -138,7 +138,11 @@ export async function handleProxyRequest(req: Request, targetUrl: string): Promi
if (v) outHeaders.set(name, v);
}
// fetch 会自动解压,转发时必须去掉长度相关头避免浏览器二次解压
- outHeaders.set('Cache-Control', 'public, max-age=3600');
+ // 图片基本不变:长缓存交给浏览器与边缘 CDN(分片 / key 仍保守 1 小时)
+ outHeaders.set(
+ 'Cache-Control',
+ contentType.startsWith('image/') ? 'public, max-age=2592000' : 'public, max-age=3600'
+ );
outHeaders.set('Access-Control-Allow-Origin', '*');
return new NextResponse(response.body, {
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 640203a..ed9de81 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -293,7 +293,9 @@ export const useAppStore = create<AppState>()(
recommendSource: 'hot-list',
recommendSourceTouched: false,
autoplayNext: true,
- imageProxyMode: 'proxy',
+ // 直连优先:豆瓣封面有公共镜像 + 内置代理两级兜底(见 buildImageCandidates),
+ // 默认省服务器流量;老用户保持已持久化的选择不受影响
+ imageProxyMode: 'direct',
customImageProxy: '',
addCustomApi: (api) => {
diff --git a/src/lib/utils.test.ts b/src/lib/utils.test.ts
new file mode 100644
index 0000000..d476fef
--- /dev/null
+++ b/src/lib/utils.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+import { buildImageCandidates, buildImageUrl } from './utils';
+
+describe('buildImageUrl', () => {
+ it('proxy 模式走查询串形式(路径形式会被 EdgeOne 等网关归一化破坏)', () => {
+ expect(buildImageUrl('https://img3.doubanio.com/a.jpg', 'proxy', '')).toBe(
+ '/api/proxy?url=' + encodeURIComponent('https://img3.doubanio.com/a.jpg')
+ );
+ });
+
+ it('direct 与 custom 模式', () => {
+ expect(buildImageUrl('https://x.com/a.jpg', 'direct', '')).toBe('https://x.com/a.jpg');
+ expect(buildImageUrl('https://x.com/a.jpg', 'custom', 'https://p.example.com/?u=')).toBe(
+ 'https://p.example.com/?u=' + encodeURIComponent('https://x.com/a.jpg')
+ );
+ expect(buildImageUrl(undefined, 'proxy', '')).toBeUndefined();
+ });
+});
+
+describe('buildImageCandidates', () => {
+ const DOUBAN = 'https://img3.doubanio.com/view/photo/m/poster.jpg';
+
+ it('direct 模式豆瓣图:直连 → 双镜像 → 内置代理', () => {
+ expect(buildImageCandidates(DOUBAN, 'direct', '')).toEqual([
+ DOUBAN,
+ 'https://img.doubanio.cmliussss.net/view/photo/m/poster.jpg',
+ 'https://img.doubanio.cmliussss.com/view/photo/m/poster.jpg',
+ '/api/proxy?url=' + encodeURIComponent(DOUBAN),
+ ]);
+ });
+
+ it('direct 模式非豆瓣图:直连 → 内置代理(无镜像候选)', () => {
+ expect(buildImageCandidates('https://bdstatic.com/x.jpg', 'direct', '')).toEqual([
+ 'https://bdstatic.com/x.jpg',
+ '/api/proxy?url=' + encodeURIComponent('https://bdstatic.com/x.jpg'),
+ ]);
+ });
+
+ it('镜像改写不命中 img\\d+ 子域时去重,不产生重复候选', () => {
+ const cands = buildImageCandidates('https://doubanio.com/a.jpg', 'direct', '');
+ expect(new Set(cands).size).toBe(cands.length);
+ expect(cands[0]).toBe('https://doubanio.com/a.jpg');
+ });
+
+ it('proxy / custom 模式为单一候选', () => {
+ expect(buildImageCandidates(DOUBAN, 'proxy', '')).toHaveLength(1);
+ expect(buildImageCandidates(DOUBAN, 'custom', 'https://p.example.com/?u=')).toHaveLength(1);
+ expect(buildImageCandidates(undefined, 'direct', '')).toEqual([]);
+ });
+});
diff --git a/src/lib/utils.ts b/src/lib/utils.ts
index ca04879..2266b8c 100644
--- a/src/lib/utils.ts
+++ b/src/lib/utils.ts
@@ -50,6 +50,31 @@ export function buildImageUrl(
return url;
}
+/**
+ * 封面图降级候选链,direct 模式下由 SmartImage 按序尝试(onError 逐级回退):
+ * - 豆瓣图(img*.doubanio.com):原站直连 → cmliussss 公共镜像(腾讯 / 阿里)→ 内置代理。
+ * doubanio 反爬对外域与空 Referer 分别返回 403 / 418,纯前端无法绕过;
+ * 公共镜像实测直连可用,置于自家代理之前以节省服务器流量。
+ * - 其他图床:原站直连 → 内置代理。
+ * proxy / custom 模式为单一地址,无降级链。
+ */
+export function buildImageCandidates(
+ url: string | undefined,
+ mode: 'direct' | 'proxy' | 'custom',
+ customTemplate: string
+): string[] {
+ const built = buildImageUrl(url, mode, customTemplate);
+ if (!built) return [];
+ if (mode !== 'direct' || !url) return [built];
+ const candidates = [built];
+ if (url.includes('doubanio.com')) {
+ candidates.push(url.replace(/img\d+\.doubanio\.com/g, 'img.doubanio.cmliussss.net'));
+ candidates.push(url.replace(/img\d+\.doubanio\.com/g, 'img.doubanio.cmliussss.com'));
+ }
+ candidates.push(`/api/proxy?url=${encodeURIComponent(url)}`);
+ return [...new Set(candidates)];
+}
+
export function validateSourceUrl(url: string): boolean {
return /^https?:\/\/.+/.test(url);
}