Skip to content

Commit

Permalink
fix(web): enable cdn remote image in preview
Browse files Browse the repository at this point in the history
  • Loading branch information
Chilfish committed Feb 28, 2024
1 parent cc620f2 commit f7f771e
Show file tree
Hide file tree
Showing 8 changed files with 95 additions and 32 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
},
"dependencies": {
"@vueuse/core": "^10.8.0",
"destr": "^2.0.3",
"pinia": "^2.1.7",
"vue": "^3.4.19",
"vue-router": "^4.3.0"
Expand Down
28 changes: 28 additions & 0 deletions packages/core/src/utils/image.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { imgCdn, imgViewSrc } from '../constants'
import { storage } from './index'

/**
* 将图片的远程 url 替换为本地图片
* 格式:域名-文件名
*/
export function replaceImg(img: string) {
if (!img)
return imgViewSrc

if (img.includes('data:image') || img.startsWith(imgCdn))
return img

const useCdn = storage<boolean>('useCdn', false)

if (useCdn) {
const { pathname } = new URL(img)
return `https://cdn.ipfsscan.io/weibo${pathname}`
}

const name = img.split('/').pop()?.replace(/\?.+/, '') // 同时去除 params
const prefix = img.match(/^(?:https?:\/\/)?([^:\/\n]+)/im)?.[1] // 域名

if (!prefix || !name)
return img
return `/assets/img/${prefix}-${name}`
}
11 changes: 11 additions & 0 deletions packages/core/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
import { destr } from 'destr'
import type { FetchOptions } from '@types'

export * from './parse'
export * from './dom'
export * from './protocol'
export * from './fetch'
export * from './image'

export const isElectron = import.meta.env.VITE_IS_ELECTRON === 'true'

export const isInMonkey = typeof document !== 'undefined' ? document.URL.includes('weibo.com') : false

export const referrerPolicy = isInMonkey ? 'origin' : 'no-referrer'

export function storage<T>(key: string, defaultVal: T) {
const str = localStorage.getItem(key)
if (str === null) {
localStorage.setItem(key, JSON.stringify(defaultVal))
return defaultVal
}
return destr<T>(str)
}

export function delay(ms = 2000) {
const randomMs = Math.random() * ms + 1000
return new Promise(resolve => setTimeout(resolve, randomMs))
Expand Down
30 changes: 8 additions & 22 deletions packages/core/src/utils/parse.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import type { CardInfo, Comment, FetchOptions, ParseResult, PicInfo, Post } from '@types'
import type {
CardInfo,
Comment,
FetchOptions,
ParseResult,
PicInfo,
Post,
} from '@types'
import { fetchComments, fetchLongText } from '../services'
import { imgViewSrc } from '../constants'
import { imgCdn } from './../constants/index'
import { getOptions } from '.'

export const weibo = 'https://weibo.com'
Expand Down Expand Up @@ -34,25 +39,6 @@ export function parseText(text?: string) {
return parsed
}

/**
* 将图片的远程 url 替换为本地图片
* 格式:域名-文件名
*/
export function replaceImg(img?: string) {
if (!img)
return imgViewSrc

if (img.includes('data:image') || img.startsWith(imgCdn))
return img

const name = img.split('/').pop()?.replace(/\?.+/, '') // 同时去除 params
const prefix = img.match(/^(?:https?:\/\/)?([^:\/\n]+)/im)?.[1] // 域名

if (!prefix || !name)
return img
return `/assets/img/${prefix}-${name}`
}

/**
* 提取原图链接
*/
Expand Down
9 changes: 9 additions & 0 deletions packages/ui/src/MainHeader.vue
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const headerStyle = computed(() => {
const router = useRouter()
const route = useRoute()
const searchInput = ref(route.query?.q?.toString() || '')
const useLocalImage = useStorage('useCdn', false)
async function search() {
const res = await usePostStore().searchText(searchInput.value)
Expand Down Expand Up @@ -56,6 +57,14 @@ onMounted(() => {
>
</form>

<!-- TODO: 设成 settings 的弹窗,来手动设置图床链接 -->
<div>
使用远程图片
<n-switch
v-model:value="useLocalImage"
/>
</div>

<Dark />
</header>
</template>
7 changes: 7 additions & 0 deletions packages/ui/src/MainImage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ const props = withDefaults(defineProps<{
const realSrc = ref(props.src)
const imgRef = ref<any>()
const disconnectFn = ref<() => void>()
const useCdn = useStorage('useCdn', false)
watch(useCdn, () => {
realSrc.value = replaceImg(props.src)
imgRef.value.imageRef.src = realSrc.value
imgRef.value.imageRef.parentElement.classList.remove('img-error')
})
onMounted(() => {
const img = imgRef.value.imageRef as HTMLImageElement
Expand Down
22 changes: 20 additions & 2 deletions packages/ui/src/post/Meta.vue
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
<script setup lang="ts">
import type { Comment, Post, Retweet } from '@types'
import { useRoute } from 'vue-router'
const props = defineProps<{
meta: Post | Comment | Retweet
isBody?: boolean
}>()
const date = useDateFormat(props.meta.created_at, 'YY-MM-DD HH:mm dddd')
const route = useRoute()
const { origin } = document.location
const url = computed(() =>
`${origin}${route.fullPath.replace(/#.+/, '')}#${(props.meta as any).mblogid}`,
)
const message = useMessage()
const { copy } = useClipboard({
source: url,
})
</script>

<template>
Expand All @@ -15,13 +28,18 @@ const date = useDateFormat(props.meta.created_at, 'YY-MM-DD HH:mm dddd')
>
<a
v-if="'mblogid' in meta && isBody"
:href="`#${meta.mblogid}`"
:href="url"
class="copy-id opacity-0 transition-opacity"
@click="() => {
copy()
message.success('复制成功')
}"
>
复制链接
复制本地链接
</a>

<a
v-if="'detail_url' in meta"
:href="meta.detail_url"
target="_blank"
>
Expand Down
19 changes: 11 additions & 8 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit f7f771e

Please sign in to comment.