Skip to content

Commit

Permalink
feat: 增加cookie仅用于画图选项
Browse files Browse the repository at this point in the history
  • Loading branch information
weaigc committed Aug 16, 2023
1 parent b57942c commit d9ebab5
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 11 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ https://bing.github1s.tk

## 安装和使用

> 由于目前微软封杀比较严重,推荐优先使用 [部署 Huggingface](#部署到-huggingface)
* 使用 Node 启动

```bash
Expand Down
22 changes: 19 additions & 3 deletions src/components/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@ import {
} from '@/components/ui/dialog'
import { Button } from './ui/button'
import { Input } from './ui/input'
import { ChunkKeys, parseCookies, extraCurlFromCookie, randomIP, encodeHeadersToCookie } from '@/lib/utils'
import { ChunkKeys, parseCookies, extraCurlFromCookie, encodeHeadersToCookie, getCookie, setCookie } from '@/lib/utils'
import { ExternalLink } from './external-link'
import { useCopyToClipboard } from '@/lib/hooks/use-copy-to-clipboard'


export function Settings() {
const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 })
const [loc, setLoc] = useAtom(hashAtom)
const [curlValue, setCurlValue] = useState(extraCurlFromCookie(parseCookies(document.cookie, ChunkKeys)))
const [imageOnly, setImageOnly] = useState(getCookie('IMAGE_ONLY') !== '0')
const [enableTTS, setEnableTTS] = useAtom(voiceAtom)

useEffect(() => {
Expand Down Expand Up @@ -58,6 +60,19 @@ export function Settings() {
placeholder="在此填写用户信息,格式: curl 'https://www.bing.com/turing/captcha/challenge' ..."
onChange={e => setCurlValue(e.target.value)}
/>
<div className="flex gap-2">
身份信息仅用于画图(推荐)
<Switch
checked={imageOnly}
className={`${imageOnly ? 'bg-blue-600' : 'bg-gray-200'} relative inline-flex h-6 w-11 items-center rounded-full`}
onChange={(checked: boolean) => setImageOnly(checked)}
>
<span
className={`${imageOnly ? 'translate-x-6' : 'translate-x-1'} inline-block h-4 w-4 transform rounded-full bg-white transition`}
/>
</Switch>
</div>

<Button variant="ghost" className="bg-[#F5F5F5] hover:bg-[#F2F2F2]" onClick={() => copyToClipboard(btoa(curlValue))}>
转成 BING_HEADER 并复制
</Button>
Expand All @@ -71,16 +86,17 @@ export function Settings() {
if (headerValue) {
try {
headerValue = atob(headerValue)
} catch (e) {}
} catch (e) { }
if (!/^\s*curl ['"]https:\/\/www\.bing\.com\/turing\/captcha\/challenge['"]/.test(headerValue)) {
toast.error('格式不正确')
return
}
const maxAge = 86400 * 30
encodeHeadersToCookie(headerValue).forEach(cookie => document.cookie = `${cookie}; Max-Age=${maxAge}; Path=/; SameSite=None; Secure`)
} else {
[...ChunkKeys, 'BING_COOKIE', 'BING_UA', 'BING_IP'].forEach(key => document.cookie = `${key}=; Path=/; SameSite=None; Secure`)
[...ChunkKeys, 'BING_COOKIE', 'BING_UA', 'BING_IP'].forEach(key => setCookie(key, ''))
}
setCookie('IMAGE_ONLY', imageOnly ? '1' : '0')

toast.success('保存成功')
setLoc('')
Expand Down
2 changes: 1 addition & 1 deletion src/lib/bots/bing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export class BingWebBot {
}

if (!resp?.result) {
throw new ChatError('Invalid response', ErrorCode.UNKOWN_ERROR)
throw new ChatError('你的 VPS 或代理可能被封禁,如有疑问,请前往 https://github.com/weaigc/bingo 咨询', ErrorCode.UNKOWN_ERROR)
}

const { value, message } = resp.result || {}
Expand Down
28 changes: 24 additions & 4 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ export function randomIP() {
return `11.${random(104, 107)}.${random(1, 255)}.${random(1, 255)}`
}

export const defaultUID = Math.random().toString(36).slice(2)

export function parseHeadersFromCurl(content: string) {
const re = /-H '([^:]+):\s*([^']+)/mg
const headers: HeadersInit = {}
Expand Down Expand Up @@ -76,6 +78,16 @@ export function parseCookie(cookie: string, cookieName: string) {
return targetCookie ? decodeURIComponent(targetCookie).trim() : cookie.indexOf('=') === -1 ? cookie.trim() : ''
}

export function setCookie(key: string, value: string) {
const maxAge = 86400 * 30
document.cookie = `${key}=${value || ''}; Path=/; Max-Age=${maxAge}; SameSite=None; Secure`
}

export function getCookie(cookieName: string) {
const re = new RegExp(`(?:[; ]|^)${cookieName}=([^;]*)`)
return re.test(document.cookie) ? RegExp.$1 : ''
}

export function parseCookies(cookie: string, cookieNames: string[]) {
const cookies: { [key: string]: string } = {}
cookieNames.forEach(cookieName => {
Expand All @@ -91,25 +103,33 @@ export function parseUA(ua?: string, default_ua = DEFAULT_UA) {
return / EDGE?/i.test(decodeURIComponent(ua || '')) ? decodeURIComponent(ua!.trim()) : default_ua
}

export function createHeaders(cookies: Partial<{ [key: string]: string }>, defaultHeaders?: Partial<{ [key: string]: string }>) {
export function createHeaders(cookies: Partial<{ [key: string]: string }>, defaultHeaders?: Partial<{ [key: string]: string }>, type?: string) {
let {
BING_COOKIE = process.env.BING_COOKIE,
BING_UA = process.env.BING_UA,
BING_IP = process.env.BING_IP,
BING_HEADER = process.env.BING_HEADER,
IMAGE_ONLY = process.env.IMAGE_ONLY ?? '1',
} = cookies

if (BING_HEADER) {
return extraHeadersFromCookie({
const headers = extraHeadersFromCookie({
BING_HEADER,
...cookies,
})
}) || {}
if (/^(1|true|yes)$/.test(String(IMAGE_ONLY)) && type !== 'image') {
// 仅画图时设置 cookie
headers.cookie = `_U=${defaultUID}`
}
if (headers['user-agent']) {
return headers
}
}

const ua = parseUA(BING_UA)

if (!BING_COOKIE) {
BING_COOKIE = defaultHeaders?.IMAGE_BING_COOKIE || 'xxx' // hf 暂时不用 Cookie 也可以正常使用
BING_COOKIE = defaultHeaders?.IMAGE_BING_COOKIE || defaultUID // hf 暂时不用 Cookie 也可以正常使用
}

const parsedCookie = parseCookie(BING_COOKIE, '_U')
Expand Down
4 changes: 2 additions & 2 deletions src/pages/api/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { NextApiRequest, NextApiResponse } from 'next'
import { fetch, debug } from '@/lib/isomorphic'
import { createHeaders } from '@/lib/utils'

// const API_ENDPOINT = 'https://www.bing.com/turing/conversation/create'
const API_ENDPOINT = 'https://edgeservices.bing.com/edgesvc/turing/conversation/create';
const API_ENDPOINT = 'https://www.bing.com/turing/conversation/create'
// const API_ENDPOINT = 'https://edgeservices.bing.com/edgesvc/turing/conversation/create';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
try {
const headers = createHeaders(req.cookies, {
IMAGE_BING_COOKIE: process.env.IMAGE_BING_COOKIE
})
}, 'image')

debug('headers', headers)
const response = await createImage(String(prompt), String(id), {
Expand Down

0 comments on commit d9ebab5

Please sign in to comment.