Skip to content

Commit

Permalink
fix: bilibili host invalid, try fix #5
Browse files Browse the repository at this point in the history
  • Loading branch information
starknt committed Aug 21, 2023
1 parent b27356d commit c279fa7
Show file tree
Hide file tree
Showing 9 changed files with 76 additions and 23 deletions.
4 changes: 4 additions & 0 deletions playground/node/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ const res = await getLongRoomId(process.env.VITE_ROOM as any)

const live = new KeepLiveTCP(res.data.room_id)

live.on('open', () => console.log('连接成功'))

live.on('close', () => console.log('断开连接'))

live.on('SEND_GIFT', (message) => { // 有礼物, 但不会被触发
console.log(message)
})
Expand Down
2 changes: 1 addition & 1 deletion playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview",
"dev:node": "esno ./node/test.ts"
"dev:node": "tsx ./node/test.ts"
},
"dependencies": {
"tiny-bilibili-ws": "workspace:*",
Expand Down
19 changes: 15 additions & 4 deletions playground/src/App.vue
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
<script setup lang="ts">
import { KeepLiveWS } from 'tiny-bilibili-ws/browser'
import { onMounted } from 'vue'
import { onMounted, ref } from 'vue'
const danmu = ref<any[]>([])
onMounted(() => {
fetch(`https://api.live.bilibili.com/room/v1/Room/mobileRoomInit?id=${import.meta.env.VITE_ROOM}`)
.then(w => w.json())
.then((data) => {
console.log(data)
})
const live = new KeepLiveWS(import.meta.env.VITE_ROOM)
console.log(live)
live.runWhenConnected(() => {
console.log(`正在监听 ${import.meta.env.VITE_ROOM}`)
Expand All @@ -22,12 +29,16 @@ onMounted(() => {
console.log(message)
})
live.on('DANMU_MSG', m => console.log(m))
live.on('DANMU_MSG', (m) => {
danmu.value.push(m)
})
})
</script>

<template>
1
<div v-for="m in danmu" :key="m">
{{ JSON.stringify(m.data) }}
</div>
</template>

<style scoped>
Expand Down
19 changes: 14 additions & 5 deletions src/base/base.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
import { WS_OP, deserialize, serialize } from './buffer'
import type { BuiltinEvent } from './cmd'
import { fromEvent } from './utils'
import type { BaseLiveClientOptions, ISocket, IWebSocket, IZlib, LiveHelloMessage, Merge, Message } from './types'
import { fromEvent, normalizeWebsocketPath } from './utils'
import type { BILIBILI_HOST, BaseLiveClientOptions, ISocket, IWebSocket, IZlib, LiveHelloMessage, Merge, Message } from './types'
import { EventEmitter } from './eventemitter'
import type { EventKey } from './eventemitter'

/// const
export enum SOCKET_HOSTS {
DEFAULT = 'hw-gz-live-comet-02.chat.bilibili.com',
HOST_TX = 'tx-bj-live-comet-02.chat.bilibili.com',
HOST_HW = 'hw-gz-live-comet-02.chat.bilibili.com',
OLD = 'broadcastlv.chat.bilibili.com',
}

export const MESSAGE_EVENT = '__message__'
export const OPEN_EVENT = '__open__'
export const ERROR_EVENT = '__error__'
export const CLOSE_EVENT = '__close__'

export const SOCKET_HOST = 'broadcastlv.chat.bilibili.com'
export const SOCKET_HOST = SOCKET_HOSTS.DEFAULT
export const NODE_SOCKET_PORT = 2243
export const WEBSOCKET_SSL_URL = `wss://${SOCKET_HOST}/sub`
export const WEBSOCKET_URL = `ws://${SOCKET_HOST}:2244/sub`
export const WEBSOCKET_PORT = 2244
export const WEBSOCKET_SSL_PORT = 443
export const WEBSOCKET_PATH = 'sub'
export const WEBSOCKET_SSL_URL = (host: BILIBILI_HOST = SOCKET_HOST, port = WEBSOCKET_SSL_PORT, path?: string) => `wss://${host}${port === 443 ? '' : `:${port}`}${normalizeWebsocketPath(path ?? WEBSOCKET_PATH)}`
export const WEBSOCKET_URL = (host: BILIBILI_HOST = SOCKET_HOST, port = WEBSOCKET_PORT, path?: string) => `ws://${host}:${port}${normalizeWebsocketPath(path ?? WEBSOCKET_PATH)}`

///

Expand Down
11 changes: 8 additions & 3 deletions src/base/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { ProtocolHeader } from './buffer'

export type BILIBILI_HOST = `${string}.chat.bilibili.com`

// @ts-expect-error PartialByKeys pk
export type PartialByKeys<O extends Record<string, any>, U = keyof O, UU = U extends keyof O ? U : never, PO = Partial<Pick<O, UU>>> =
PO & {
Expand Down Expand Up @@ -68,10 +70,10 @@ export const DEFAULT_WS_OPTIONS: Options = {
reconnectTime: 5 * 1000,
heartbeatTime: 30 * 1000,
// clientVer: '2.0.11',
// platform: 'web',
// protover: 2,
platform: 'web',
protover: 3,
// uid: 0,
// type: 2,
type: 2,
}

export interface BaseLiveClientOptions extends Options {
Expand Down Expand Up @@ -116,6 +118,9 @@ export interface AuthOptions {

export interface ConnectionOptions {
url?: string
host?: BILIBILI_HOST
port?: number
path?: string
}

export interface WSOptions extends BaseOptions, AuthOptions, ConnectionOptions {
Expand Down
4 changes: 4 additions & 0 deletions src/base/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,7 @@ export function fromEvent<T>(emitter: EventEmitter<any>, event: string, timeout?
export function toMessageData(message: Message<any>) {
return message.data
}

export function normalizeWebsocketPath(path: string) {
return path[0] === '/' ? path : `/${path}`
}
14 changes: 10 additions & 4 deletions src/browser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CLOSE_EVENT, ERROR_EVENT, LiveClient, MESSAGE_EVENT, OPEN_EVENT, WEBSOCKET_SSL_URL, WEBSOCKET_URL } from './base/base'
import { CLOSE_EVENT, ERROR_EVENT, LiveClient, MESSAGE_EVENT, OPEN_EVENT, SOCKET_HOSTS, WEBSOCKET_SSL_URL, WEBSOCKET_URL } from './base/base'
import type { BaseLiveClientOptions, IWebSocket, Merge, WSOptions } from './base/types'
import { DEFAULT_WS_OPTIONS } from './base/types'
import { parser } from './base/buffer'
Expand All @@ -21,7 +21,13 @@ export class KeepLiveWS<E extends Record<EventKey, any> = { }> extends LiveClien

constructor(roomId: number, options: WSOptions = DEFAULT_WS_OPTIONS) {
const resolvedOptions = Object.assign({}, DEFAULT_WS_OPTIONS, options)
const url = resolvedOptions.url ?? options.ssl ? WEBSOCKET_SSL_URL : WEBSOCKET_URL
const ssl = !!resolvedOptions.ssl
const url = resolvedOptions.url
?? (
ssl
? WEBSOCKET_SSL_URL(resolvedOptions.host ?? SOCKET_HOSTS.DEFAULT, resolvedOptions.port, resolvedOptions.path)
: WEBSOCKET_URL(SOCKET_HOSTS.DEFAULT, resolvedOptions.port, resolvedOptions.path)
)
const socket = new WebSocket(url)
socket.binaryType = 'arraybuffer'

Expand All @@ -35,10 +41,10 @@ export class KeepLiveWS<E extends Record<EventKey, any> = { }> extends LiveClien
close: () => {
this.ws.close()
},
reconnect: () => {
reconnect: (_url?: string) => {
this.ws?.close()
this.ws = null!
const socket = new WebSocket(resolvedOptions.url ?? options.ssl ? WEBSOCKET_SSL_URL : WEBSOCKET_URL)
const socket = new WebSocket(_url ?? url)
socket.binaryType = 'arraybuffer'
this.ws = socket
this._bindEvent(socket)
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export type { EventKey, Listener } from './base/eventemitter'
export type { Protocol, ProtocolHeader } from './base/buffer'
export type { WSOptions, TCPOptions, MessageMeta, Message, RoomResponse } from './base/types'
export type * from './base/cmd'
export { SOCKET_HOSTS, WEBSOCKET_SSL_URL, WEBSOCKET_URL } from './base/base'
25 changes: 19 additions & 6 deletions src/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import https from 'node:https'
import { Buffer } from 'node:buffer'
import type { CloseEvent, ErrorEvent } from 'ws'
import WebSocket from 'ws'
import { CLOSE_EVENT, ERROR_EVENT, LiveClient, MESSAGE_EVENT, NODE_SOCKET_PORT, OPEN_EVENT, SOCKET_HOST, WEBSOCKET_SSL_URL, WEBSOCKET_URL } from './base/base'
import { CLOSE_EVENT, ERROR_EVENT, LiveClient, MESSAGE_EVENT, NODE_SOCKET_PORT, OPEN_EVENT, SOCKET_HOST, SOCKET_HOSTS, WEBSOCKET_SSL_URL, WEBSOCKET_URL } from './base/base'
import { inflates } from './node/inflate'
import type { BaseLiveClientOptions, ISocket, IWebSocket, Merge, RoomResponse, TCPOptions, WSOptions } from './base/types'
import { DEFAULT_WS_OPTIONS } from './base/types'
Expand Down Expand Up @@ -47,7 +47,9 @@ export class KeepLiveTCP<E extends Record<EventKey, any> = { }> extends LiveClie
constructor(roomId: number, options: TCPOptions = DEFAULT_WS_OPTIONS) {
const resolvedOptions = Object.assign({}, DEFAULT_WS_OPTIONS, options)

const socket = resolvedOptions.url ? connect(resolvedOptions.url) : connect(NODE_SOCKET_PORT, SOCKET_HOST)
const socket = resolvedOptions.url
? connect(resolvedOptions.url)
: connect(resolvedOptions.port ?? NODE_SOCKET_PORT, resolvedOptions.host ?? SOCKET_HOST)

const liveOptions: BaseLiveClientOptions = {
...resolvedOptions,
Expand All @@ -59,7 +61,9 @@ export class KeepLiveTCP<E extends Record<EventKey, any> = { }> extends LiveClie
reconnect: () => {
this.tcpSocket?.end()
this.tcpSocket = null!
const socket = resolvedOptions.url ? connect(resolvedOptions.url) : connect(NODE_SOCKET_PORT, SOCKET_HOST)
const socket = resolvedOptions.url
? connect(resolvedOptions.url)
: connect(resolvedOptions.port ?? NODE_SOCKET_PORT, resolvedOptions.host ?? SOCKET_HOST)
this.tcpSocket = socket
this._bindEvent(socket)
},
Expand Down Expand Up @@ -122,8 +126,17 @@ export class KeepLiveWS<E extends Record<EventKey, any> = { }> extends LiveClien

constructor(roomId: number, options: WSOptions = DEFAULT_WS_OPTIONS) {
const resolvedOptions = Object.assign({}, DEFAULT_WS_OPTIONS, options)
const ssl = !!resolvedOptions.ssl
const url = resolvedOptions.url
?? (
ssl
? WEBSOCKET_SSL_URL(resolvedOptions.host ?? SOCKET_HOSTS.DEFAULT, resolvedOptions.port, resolvedOptions.path)
: WEBSOCKET_URL(SOCKET_HOSTS.DEFAULT, resolvedOptions.port, resolvedOptions.path)
)

const socket = new WebSocket(options.ssl ? WEBSOCKET_SSL_URL : WEBSOCKET_URL)
console.log({ url, resolvedOptions })

const socket = new WebSocket(url)

const liveOptions: BaseLiveClientOptions = {
...resolvedOptions,
Expand All @@ -139,10 +152,10 @@ export class KeepLiveWS<E extends Record<EventKey, any> = { }> extends LiveClien
close: () => {
this.ws.close()
},
reconnect: () => {
reconnect: (_url?: string) => {
this.ws?.close()
this.ws = null!
const socket = new WebSocket(options.ssl ? WEBSOCKET_SSL_URL : WEBSOCKET_URL)
const socket = new WebSocket(_url ?? url)
this.ws = socket
this._bindEvent(socket)
},
Expand Down

0 comments on commit c279fa7

Please sign in to comment.