feat(mobile): image fallback and referer

This commit is contained in:
DIYgod
2025-02-28 08:58:57 +08:00
parent 861ae35819
commit 3bc3f862c8
2 changed files with 67 additions and 25 deletions
@@ -1,6 +1,8 @@
import type { ImageProps } from "expo-image"
import { Image } from "expo-image"
import { forwardRef, useMemo } from "react"
import { forwardRef, useCallback, useMemo, useState } from "react"
import { getImageHeaders } from "@/src/lib/image"
const IMAGE_PROXY_URL = "https://webp.follow.is"
@@ -25,29 +27,37 @@ export const ProxiedImage = forwardRef<
}
}
>(({ proxy, source, ...rest }, ref) => {
const nextSrc = useMemo(() => {
if (!source) return source
if (!proxy?.height && !proxy?.width) {
return source
let nextSource: ImageProps["source"] = source
if (typeof source === "string") {
nextSource = {
uri: source,
headers: getImageHeaders(source),
}
if (typeof source === "string") {
return getImageProxyUrl({
url: source,
} else if (!source.headers) {
nextSource = {
...source,
headers: getImageHeaders(source.uri),
}
}
const finalSource = useMemo(() => {
if (!proxy?.height && !proxy?.width) {
return nextSource
}
return {
...nextSource,
uri: getImageProxyUrl({
url: nextSource.uri,
width: proxy?.width ? proxy?.width * 3 : undefined,
height: proxy?.height ? proxy?.height * 3 : undefined,
})
} else {
return {
...source,
uri: getImageProxyUrl({
url: source.uri,
width: proxy?.width ? proxy?.width * 3 : undefined,
height: proxy?.height ? proxy?.height * 3 : undefined,
}),
}
}),
}
}, [source, proxy?.height, proxy?.width])
}, [proxy?.height, proxy?.width, nextSource])
return <Image source={nextSrc} {...rest} ref={ref} />
const [isError, setIsError] = useState(false)
const onError = useCallback(() => {
setIsError(true)
}, [])
return <Image source={isError ? nextSource : finalSource} onError={onError} {...rest} ref={ref} />
})
+36 -4
View File
@@ -1,11 +1,43 @@
const imageRefererMatches = [
{
url: /^https:\/\/\w+\.sinaimg.cn/,
referer: "https://weibo.com",
},
{
url: /^https:\/\/i\.pximg\.net/,
referer: "https://www.pixiv.net",
},
{
url: /^https:\/\/cdnfile\.sspai\.com/,
referer: "https://sspai.com",
},
{
url: /^https:\/\/(?:\w|-)+\.cdninstagram\.com/,
referer: "https://www.instagram.com",
},
{
url: /^https:\/\/sp1\.piokok\.com/,
referer: "https://www.piokok.com",
force: true,
},
]
export const getImageHeaders = (url: string | undefined) => {
if (!url) return {}
if (url.startsWith("https://cdnfile.sspai.com")) {
const ua =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36"
const refererMatch = imageRefererMatches.find((item) => item.url.test(url))
if (refererMatch?.referer) {
return {
Referer: "https://sspai.com",
Referer: refererMatch.referer,
"User-Agent": ua,
}
} else {
return {
Referer: new URL(url).origin,
"User-Agent": ua,
}
}
return {}
}