Skip to content

Commit

Permalink
chore: 增加更多debug信息
Browse files Browse the repository at this point in the history
  • Loading branch information
weaigc committed Aug 20, 2023
1 parent bd5db71 commit 92977cc
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 85 deletions.
16 changes: 15 additions & 1 deletion package-lock.json

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

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.3.0",
"private": true,
"scripts": {
"dev": "cross-env DEBUG=bingo next dev --hostname 0.0.0.0",
"dev": "cross-env DEBUG=bingo* next dev --hostname 0.0.0.0",
"build": "next build",
"start": "next start",
"lint": "next lint"
Expand Down Expand Up @@ -32,6 +32,7 @@
"i18next": "^22.5.0",
"i18next-browser-languagedetector": "^7.0.2",
"idb-keyval": "^6.2.1",
"ifw": "^0.0.2",
"immer": "^9.0.19",
"inter-ui": "^3.19.3",
"jotai": "^2.2.1",
Expand Down Expand Up @@ -67,7 +68,6 @@
"tailwind-scrollbar": "^3.0.4",
"tailwindcss": "3.3.2",
"typescript": "5.1.6",
"undici": "^5.22.1",
"websocket-as-promised": "^2.0.1",
"ws": "^8.13.0"
},
Expand Down
46 changes: 27 additions & 19 deletions src/components/chat-image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ import {
ChangeEvent,
ClipboardEvent,
MouseEventHandler,
FormEvent,
useRef
useRef,
KeyboardEvent
} from "react"
import Image from 'next/image'
import PasteIcon from '@/assets/images/paste.svg'
import UploadIcon from '@/assets/images/upload.svg'
import CameraIcon from '@/assets/images/camera.svg'
import { useBing } from '@/lib/hooks/use-bing'
import { cn } from '@/lib/utils'
import { toast } from "react-hot-toast"

interface ChatImageProps extends Pick<ReturnType<typeof useBing>, 'uploadImage'> {}

Expand All @@ -33,6 +34,7 @@ export function ChatImage({ children, uploadImage }: React.PropsWithChildren<Cha
const canvasRef = useRef<HTMLCanvasElement>(null)
const mediaStream = useRef<MediaStream>()
const [panel, setPanel] = useState('none')
const [inputUrl, setInputUrl] = useState('')

const upload = useCallback((url: string) => {
if (url) {
Expand All @@ -56,15 +58,17 @@ export function ChatImage({ children, uploadImage }: React.PropsWithChildren<Cha
upload(pasteUrl)
}, [])

const onEnter = useCallback((event: FormEvent<HTMLFormElement>) => {
const onEnter = useCallback((event: KeyboardEvent<HTMLInputElement>) => {
// @ts-ignore
event.preventDefault()
event.stopPropagation()
// @ts-ignore
const inputUrl = event.target.elements.image.value
if (inputUrl) {
event.stopPropagation()
if (/^https?:\/\/.+/.test(inputUrl)) {
upload(inputUrl)
} else {
toast.error('请输入有效的图片链接')
}
}, [])
}, [inputUrl])

const openVideo: MouseEventHandler<HTMLButtonElement> = async (event) => {
event.stopPropagation()
Expand Down Expand Up @@ -123,18 +127,22 @@ export function ChatImage({ children, uploadImage }: React.PropsWithChildren<Cha
</div>
<div className="paste">
<Image alt="paste" src={PasteIcon} width={24} />
<form onSubmitCapture={onEnter}>
<input
className="paste-input"
id="sb_imgpst"
type="text"
name="image"
placeholder="粘贴图像 URL"
aria-label="粘贴图像 URL"
onPaste={onPaste}
onClickCapture={(e) => e.stopPropagation()}
/>
</form>
<input
className="paste-input"
id="sb_imgpst"
type="text"
name="image"
placeholder="粘贴图像 URL"
aria-label="粘贴图像 URL"
onPaste={onPaste}
onChange={(event) => setInputUrl(event.target.value.trim())}
onKeyDownCapture={event => {
if (event.key === 'Enter') {
onEnter(event)
}
}}
onClickCapture={(e) => e.stopPropagation()}
/>
</div>
<div className="buttons">
<button type="button" aria-label="从此设备上传">
Expand Down
11 changes: 0 additions & 11 deletions src/lib/isomorphic/browser.ts

This file was deleted.

19 changes: 5 additions & 14 deletions src/lib/isomorphic/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
'use client'

import Default from './browser'
import Debug from 'debug'
export * from 'ifw'

let exportsModel: any = {}

if (process.browser) {
Object.assign(exportsModel, require('./browser').default)
} else {
Object.assign(exportsModel, require('./node').default)
}

export default exportsModel! as typeof Default

export const fetch: typeof Default.fetch = exportsModel!.fetch
export const WebSocket: typeof Default.WebSocket = exportsModel!.WebSocket
export const debug: typeof Default.debug = exportsModel!.debug
export const debug = typeof document === 'undefined' ? Debug('bingo')
: process.env.NEXT_PUBLIC_DEBUG ? console.info.bind(console)
: () => {}
26 changes: 0 additions & 26 deletions src/lib/isomorphic/node.ts

This file was deleted.

11 changes: 4 additions & 7 deletions src/pages/api/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,10 @@ const API_ENDPOINT = 'https://www.bing.com/turing/conversation/create'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
let count = 0
let { BING_IP, ...cookies } = req.cookies
const headers = createHeaders(req.cookies)
do {
const headers = createHeaders({
...cookies,
BING_IP: BING_IP || randomIP(),
})
headers['x-forwarded-for'] = headers['x-forwarded-for'] || randomIP()
debug(`try ${count+1}`, headers['x-forwarded-for'])
const response = await fetch(API_ENDPOINT, { method: 'GET', headers })
if (response.status === 200) {
res.setHeader('set-cookie', [headers.cookie, `BING_IP=${headers['x-forwarded-for']}`]
Expand All @@ -28,9 +26,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
res.end(await response.text())
return
}
BING_IP = ''
await sleep(2000)
debug('loop', count)
headers['x-forwarded-for'] = ''
} while(count++ < 10)
res.end(JSON.stringify({
result: {
Expand Down
15 changes: 10 additions & 5 deletions src/pages/api/sydney.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import { WatchDog, createHeaders } from '@/lib/utils'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const conversationContext = req.body
const headers = createHeaders(req.cookies)
debug(headers)
const id = headers['x-forwarded-for']

debug(id, headers)
res.setHeader('Content-Type', 'text/stream; charset=UTF-8')

const ws = new WebSocket('wss://sydney.bing.com/sydney/ChatHub', {
Expand All @@ -24,15 +26,17 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const timeoutDog = new WatchDog()
ws.onmessage = (event) => {
timeoutDog.watch(() => {
debug(id, 'timeout')
ws.send(websocketUtils.packMessage({ type: 6 }))
}, 1500)
}, 3000)
closeDog.watch(() => {
debug(id, 'timeout close')
ws.close()
}, 10000)
}, 20000)
res.write(event.data)
if (/\{"type":([367])\}/.test(String(event.data))) {
const type = parseInt(RegExp.$1, 10)
debug('connection type', type)
debug(id, 'connection type', type)
if (type === 3) {
ws.close()
} else {
Expand All @@ -44,7 +48,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
ws.onclose = () => {
timeoutDog.reset()
closeDog.reset()
debug('connection close')
debug(id, 'ws close')
res.end()
}

Expand All @@ -53,6 +57,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
ws.send(websocketUtils.packMessage({ type: 6 }))
ws.send(websocketUtils.packMessage(BingWebBot.buildChatRequest(conversationContext!)))
req.socket.once('close', () => {
debug(id, 'connection close')
ws.close()
if (!res.closed) {
res.end()
Expand Down

0 comments on commit 92977cc

Please sign in to comment.