code2024/bingo
0
1import { clsx, type ClassValue } from 'clsx'2import { customAlphabet } from 'nanoid'3import { twMerge } from 'tailwind-merge'4 5export function cn(...inputs: ClassValue[]) {6 return twMerge(clsx(inputs))7}8 9export const nanoid = customAlphabet(10 '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',11 712) // 7-character random string13 14export function createChunkDecoder() {15 const decoder = new TextDecoder()16 return function (chunk: Uint8Array | undefined): string {17 if (!chunk) return ''18 return decoder.decode(chunk, { stream: true })19 }20}21 22export function random (start: number, end: number) {23 return start + Math.ceil(Math.random() * (end - start))24}25 26export function randomIP() {27 return `11.${random(104, 107)}.${random(1, 255)}.${random(1, 255)}`28}29 30export const defaultUID = Math.random().toString(36).slice(2)31 32export function parseHeadersFromCurl(content: string) {33 const re = /-H '([^:]+):\s*([^']+)/mg34 const headers: HeadersInit = {}35 content = content.replaceAll('-H "', '-H \'').replaceAll('" ^', '\'\\').replaceAll('^\\^"', '"') // 将 cmd curl 转成 bash curl36 content.replace(re, (_: string, key: string, value: string) => {37 headers[key] = value38 return ''39 })40 41 return headers42}43 44export const ChunkKeys = ['BING_HEADER', 'BING_HEADER1', 'BING_HEADER2']45export function encodeHeadersToCookie(content: string) {46 const base64Content = btoa(content)47 const contentChunks = base64Content.match(/.{1,4000}/g) || []48 return ChunkKeys.map((key, index) => `${key}=${contentChunks[index] ?? ''}`)49}50 51export function extraCurlFromCookie(cookies: Partial<{ [key: string]: string }>) {52 let base64Content = ''53 ChunkKeys.forEach((key) => {54 base64Content += (cookies[key] || '')55 })56 try {57 return atob(base64Content)58 } catch(e) {59 return ''60 }61}62 63export function extraHeadersFromCookie(cookies: Partial<{ [key: string]: string }>) {64 return parseHeadersFromCurl(extraCurlFromCookie(cookies))65}66 67export function formatDate(input: string | number | Date): string {68 const date = new Date(input)69 return date.toLocaleDateString('en-US', {70 month: 'long',71 day: 'numeric',72 year: 'numeric'73 })74}75 76export function parseCookie(cookie: string, cookieName: string) {77 const targetCookie = new RegExp(`(?:[; ]|^)${cookieName}=([^;]*)`).test(cookie) ? RegExp.$1 : cookie78 return targetCookie ? decodeURIComponent(targetCookie).trim() : cookie.indexOf('=') === -1 ? cookie.trim() : ''79}80 81export function setCookie(key: string, value: string) {82 const maxAge = 86400 * 3083 document.cookie = `${key}=${value || ''}; Path=/; Max-Age=${maxAge}; SameSite=None; Secure`84}85 86export function getCookie(cookieName: string) {87 const re = new RegExp(`(?:[; ]|^)${cookieName}=([^;]*)`)88 return re.test(document.cookie) ? RegExp.$1 : ''89}90 91export function parseCookies(cookie: string, cookieNames: string[]) {92 const cookies: { [key: string]: string } = {}93 cookieNames.forEach(cookieName => {94 cookies[cookieName] = parseCookie(cookie, cookieName)95 })96 return cookies97}98 99export const DEFAULT_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.0.0'100export const DEFAULT_IP = process.env.BING_IP || randomIP()101 102export function parseUA(ua?: string, default_ua = DEFAULT_UA) {103 return / EDGE?/i.test(decodeURIComponent(ua || '')) ? decodeURIComponent(ua!.trim()) : default_ua104}105 106export function createHeaders(cookies: Partial<{ [key: string]: string }>, defaultHeaders?: Partial<{ [key: string]: string }>, type?: string) {107 let {108 BING_COOKIE = process.env.BING_COOKIE,109 BING_UA = process.env.BING_UA,110 BING_IP = process.env.BING_IP,111 BING_HEADER = process.env.BING_HEADER,112 IMAGE_ONLY = process.env.IMAGE_ONLY ?? '1',113 } = cookies114 115 if (BING_HEADER) {116 const headers = extraHeadersFromCookie({117 BING_HEADER,118 ...cookies,119 }) || {}120 if (/^(1|true|yes)$/.test(String(IMAGE_ONLY)) && type !== 'image') {121 // 仅画图时设置 cookie122 headers.cookie = `_U=${defaultUID}`123 }124 if (headers['user-agent']) {125 return headers126 }127 }128 129 const ua = parseUA(BING_UA)130 131 if (!BING_COOKIE) {132 BING_COOKIE = defaultHeaders?.IMAGE_BING_COOKIE || defaultUID // hf 暂时不用 Cookie 也可以正常使用133 }134 135 const parsedCookie = parseCookie(BING_COOKIE, '_U')136 if (!parsedCookie) {137 throw new Error('Invalid Cookie')138 }139 return {140 'x-forwarded-for': BING_IP || DEFAULT_IP,141 'Accept-Encoding': 'gzip, deflate, br',142 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',143 'User-Agent': ua!,144 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32',145 cookie: `_U=${parsedCookie}` || '',146 }147}148 149export class WatchDog {150 private tid = 0151 watch(fn: Function, timeout = 2000) {152 clearTimeout(this.tid)153 this.tid = setTimeout(fn, timeout + Math.random() * 1000)154 }155 reset() {156 clearTimeout(this.tid)157 }158}159 