76 lines
2.1 KiB
TypeScript
76 lines
2.1 KiB
TypeScript
|
import db from '@/db'
|
||
|
|
||
|
interface AdverLink {
|
||
|
id: string
|
||
|
tag: string
|
||
|
adverLink: string
|
||
|
}
|
||
|
type AdverParams = Omit<AdverLink, 'adverLink'> & {
|
||
|
adverParams: string
|
||
|
}
|
||
|
|
||
|
type AdverData = {
|
||
|
links: AdverLink[]
|
||
|
params: AdverParams[]
|
||
|
expiration: number
|
||
|
}
|
||
|
|
||
|
const fetchAdverConfig = async () => {
|
||
|
return Promise.allSettled([
|
||
|
fetch('https://api.iyuntab.com/adverLink/params').then((res) => res.json()),
|
||
|
fetch('https://api.iyuntab.com/adverLink/link').then((res) => res.json())
|
||
|
]).then((res) => {
|
||
|
const result: AdverData = { links: [], params: [], expiration: Date.now() + 1000 * 60 * 60 * 4 }
|
||
|
if (res[0].status === 'fulfilled') {
|
||
|
result.params = res[0].value
|
||
|
}
|
||
|
if (res[1].status === 'fulfilled') {
|
||
|
result.links = res[1].value
|
||
|
}
|
||
|
return db.setItem('adverInfo', result).then(() => result)
|
||
|
})
|
||
|
}
|
||
|
export function getAdverConfig() {
|
||
|
return db
|
||
|
.getItem<{ links: AdverLink[]; params: AdverParams[]; expiration: number }>('adverInfo')
|
||
|
.then((res) => {
|
||
|
if (!res || res.expiration < Date.now()) {
|
||
|
return fetchAdverConfig()
|
||
|
}
|
||
|
return Promise.resolve(res)
|
||
|
})
|
||
|
}
|
||
|
|
||
|
async function checkWithAdver(_url: string) {
|
||
|
try {
|
||
|
const config = await getAdverConfig()
|
||
|
const tag = _url.match(/(?<=http(s?):\/\/).*/g)?.[0] || _url
|
||
|
for (const item of config.params) {
|
||
|
if (tag.startsWith(item.tag)) {
|
||
|
const params = new URLSearchParams(item.adverParams)
|
||
|
const origin = new URLSearchParams(_url.includes('?') ? _url : _url + '?')
|
||
|
for (const key of params.keys()) {
|
||
|
const value = params.get(key)
|
||
|
if (value) {
|
||
|
origin.set(key, value)
|
||
|
}
|
||
|
}
|
||
|
return decodeURIComponent(origin.toString())
|
||
|
}
|
||
|
}
|
||
|
for (const item of config.links) {
|
||
|
if (item.tag.startsWith(tag)) {
|
||
|
return item.adverLink
|
||
|
}
|
||
|
}
|
||
|
return _url
|
||
|
} catch (_) {
|
||
|
return _url
|
||
|
}
|
||
|
}
|
||
|
export default async function jump(_url: string) {
|
||
|
const url = _url.startsWith('http') ? _url : `https://${_url}`
|
||
|
const used = await checkWithAdver(url)
|
||
|
window.open(used, '_blank')
|
||
|
}
|