2024-04-07 01:53:46 +08:00
|
|
|
"use client";
|
2024-04-07 02:02:08 +08:00
|
|
|
import { useState, useEffect, useCallback, useRef } from "react";
|
2024-04-07 01:53:46 +08:00
|
|
|
import useWebSocket, { ReadyState } from "react-use-websocket";
|
|
|
|
import MessageDispatcher from "./message";
|
|
|
|
import { Token } from "@/lib/types";
|
|
|
|
|
|
|
|
const MOMO_IM_URL = "wss://live-ws.immomo.com/ws/im";
|
|
|
|
|
|
|
|
export const Danmu: React.FC<{ token: Token }> = ({ token }) => {
|
|
|
|
const [messageHistory, setMessageHistory] = useState<MessageEvent<any>[]>([]);
|
2024-04-07 02:02:08 +08:00
|
|
|
const ref = useRef<HTMLDivElement>(null);
|
2024-04-07 01:53:46 +08:00
|
|
|
|
|
|
|
const { sendMessage, lastMessage, readyState } = useWebSocket(MOMO_IM_URL, {
|
|
|
|
heartbeat: {
|
|
|
|
message: () => {
|
|
|
|
const pingMessage = {
|
|
|
|
msg_id: 2,
|
|
|
|
client_time: Date.now(),
|
|
|
|
type: "Ping",
|
|
|
|
data: {},
|
|
|
|
};
|
|
|
|
return JSON.stringify(pingMessage);
|
|
|
|
},
|
|
|
|
interval: 5000,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
const momoId = token.uid;
|
|
|
|
const roomId = "1476810196216";
|
|
|
|
const momoToken = token.token;
|
|
|
|
|
|
|
|
const clientTime = Date.now();
|
|
|
|
const data = {
|
|
|
|
msg_id: 1,
|
|
|
|
client_time: clientTime,
|
|
|
|
type: "Sauth",
|
|
|
|
data: {
|
|
|
|
momoid: momoId,
|
|
|
|
roomid: roomId,
|
|
|
|
role: 6,
|
|
|
|
isVisitor: false,
|
|
|
|
token: momoToken,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (ReadyState.OPEN === readyState) {
|
|
|
|
sendMessage(JSON.stringify(data));
|
|
|
|
}
|
|
|
|
}, [readyState]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (lastMessage !== null) {
|
|
|
|
if (lastMessage.data) {
|
|
|
|
const message = JSON.parse(lastMessage.data);
|
|
|
|
if (message.type === "pong") {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
console.log(message);
|
|
|
|
setMessageHistory((prev) => prev.concat(message));
|
2024-04-07 02:02:08 +08:00
|
|
|
if (ref.current) {
|
|
|
|
setTimeout(() => {
|
|
|
|
ref.current.scrollTop = ref.current.scrollHeight;
|
|
|
|
}, 0);
|
|
|
|
}
|
2024-04-07 01:53:46 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}, [lastMessage]);
|
|
|
|
|
|
|
|
return (
|
2024-04-07 02:02:08 +08:00
|
|
|
<div className="h-[50vh] overflow-auto" ref={ref}>
|
2024-04-07 01:53:46 +08:00
|
|
|
{messageHistory.map((message, idx) => (
|
|
|
|
<MessageDispatcher key={idx} message={message} />
|
|
|
|
))}
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
};
|