PageSourceSearch

https://lingyuzhao.top/js/webSocketHandler.js

js lingyuzhao.top collected 2026-10-06 13:16:07 UTC 8,656 bytes, 240 lines download raw bytes

1function addChatTextBlock(e, json, isSelf = true) {
2    const div1 = document.createElement("div");
3    div1.className = 'data-row';
4    if (isMobileDevice()) {
5        div1.classList.add("data-row-Mobile")
6    }
7    const div2 = document.createElement("div");
8    div2.className = "sendDateTime";
9    div2.innerText = getDate(new Date(json.sendDate));
10    div1.appendChild(div2);
11    const br = document.createElement("br");
12    div1.appendChild(br);
13    const img = document.createElement("img");
14    const userConfJson = isSelf ? USER_CONF : USER_CONF_TEMP;
15    img.className = "headSculpture";
16    const b = userConfJson.headSculpture === undefined;
17    img.src = b ? 'image/logo.svg' : userConfJson.headSculpture[1];
18    img.alt = my_temp.name;
19    img.style.margin = "1vh;";
20    if (!b) {
21        img.onclick = () => toPersonHomePage(my_temp)
22    }
23    div1.appendChild(img)
24    const div3 = document.createElement("div");
25    div3.className = "container left textDataBlock";
26    div3.style.backgroundColor = isSelf ? '#fff' : '#b2c3ff'
27    div3.id = json.id;
28    editormd.markdownToHTML(div3, {
29        flowChart: true,
30        htmlDecode: "video,style,iframe,sub,sup",
31        markdown: json.data,
32        emoji: true,
33        path: "editor.md/lib/"
34    })
35    div1.appendChild(div3);
36    e.appendChild(div1);
37    // 移动到最底部
38    e.scrollTop = e.scrollHeight;
39}
40
41class Ly_MblOnline {
42    /**
43     * 当前登录的在线人数 以及 所有人的在线人数
44     * @type {number}
45     */
46    static nowLoginCount = 0;
47    static nowNoLoginUserCount = 0;
48
49    /**
50     * 设置当前登录的在线人数,下次刷新时 数据将被展示!
51     * @param count
52     */
53    static setNowLoginCount(count) {
54        Ly_MblOnline.nowLoginCount = count;
55    }
56
57    /**
58     * 设置当前在线未登录人数,下次刷新时 数据将被展示!
59     * @param count
60     */
61    static setNowNoLoginUserCount(count) {
62        Ly_MblOnline.nowNoLoginUserCount = count;
63    }
64}
65
66class LY_MblChat {
67
68    static webSocket;
69
70    static initChat(okFun, closeConnectFun = undefined, reConnectFun = undefined, checkConnect = undefined) {
71
72        function extracted(wsUrl) {
73            if (LY_MblChat.webSocket !== undefined) {
74                // 关闭之前的连接
75                LY_MblChat.webSocket.close(3024, 'Manual close, do not reconnect');
76                // 清除旧的 WebSocket 实例
77                LY_MblChat.webSocket = undefined;
78            }
79            LY_MblChat.webSocket = new WebSocket(wsUrl);
80            initChatSocket(LY_MblChat.webSocket, wsUrl, closeConnectFun, reConnectFun, checkConnect);
81            okFun(LY_MblChat.webSocket);
82        }
83
84        // 获取到 codeBookWebSocket 的认证
85        CodeBookAuthentication(
86            "codeBookWebSocket",
87            (dataTemp) => {
88                const wsUrl = char_host_href() + WEB_CONF['CHAT_HANDLER'] + '?' + 'userId=' + dataTemp.thirdPartyUserID + '&passwd=' + dataTemp.thirdPartyKey;
89                extracted(wsUrl);
90            },
91            (_) => {
92                // 认为没有登录 这个情况也可以建立连接 只是建立的连接中没有用户信息
93                const wsUrl = char_host_href() + WEB_CONF['CHAT_HANDLER'] + '?noLogin=true';
94                extracted(wsUrl);
95            }
96        )
97    }
98}
99
100let getWebSocketHandler = () => undefined;
101
102// 准备计时器 刷新当前在线人数
103setInterval(() => {
104    const webSocketHandler = getWebSocketHandler();
105    if (!webSocketHandler) {
106        return;
107    }
108    webSocketHandler.send(JSON.stringify(
109        {
110            id: getRandomInt(-40690000, 40690000),
111            sendId: -1,
112            recId: -1,
113            command: "updateOnlineToClient"
114        }
115    ));
116}, 5000);
117
118/**
119 * 初始化聊天的websocket 在这里会被赋予事件函数
120 * @param webSocket 需要被初始化的websocket
121 * @param wsUrl websocket 的url 重连需要用
122 * @param closeConnectFun 关闭连接的函数 在这里不要重新连接 因为内部有重新连接的逻辑
123 * @param reConnectFun 重连发生之后要调用的函数 这里会传递最新的 webSocket
124 * @param checkConnect 检查连接是否可用
125 */
126function initChatSocket(webSocket, wsUrl, closeConnectFun = undefined, reConnectFun = undefined, checkConnect = undefined) {
127    webSocket.onopen = function () {
128        getWebSocketHandler = () => webSocket;
129    }
130
131    webSocket.onerror = function (error) {
132        if (getNOW_PAGE() === 'chat.html') {
133            addChatTextBlock(data_message, {
134                id: parse.id,
135                sendId: parse.sendId,
136                sendDate: parse.sendDate,
137                data: error.toString()
138            }, false)
139        } else {
140            console.error(error)
141        }
142    };
143
144    function extractedMassage(parse) {
145        if (confirm("您收到了[" + parse.sendName + "]发来的私信:" + parse.data + "; 是否需要立刻查看?")) {
146            getUserByUserIdOrName(parse.sendId, parse.sendName).then((res) => {
147                if (WEB_CONF['RES_RETURN_OK_VALUE'] === res[WEB_CONF.RES_RETURN]) {
148                    toChatPage(res[parse.sendName])
149                } else {
150                    alert("跳转失败,无法获取到发送者的信息!!!")
151                }
152            })
153        }
154    }
155
156    const command_handler = {
157        "updateOnlineToClient": function (parse) {
158            // 更新当前登录用户
159            Ly_MblOnline.setNowLoginCount(parse['onlineUserCount'] ? parse['onlineUserCount'] : 0);
160            // 更新当前未登录用户
161            Ly_MblOnline.setNowNoLoginUserCount(parse['noLoginCount'] ? parse['noLoginCount'] : 0);
162        },
163        "jokBox": function (parse) {
164            // 弹窗
165            jokerBoxPopUp.show(parse.data);
166        },
167        "logout": function (parse) {
168            // 强制退出登录
169            logout(true, parse.data ? parse.data : "您已被强制退出登录!");
170        }
171    }
172
173    webSocket.onmessage = function (event) {
174        const parse = JSON.parse(event.data);
175        const commandHandlerElement = command_handler[parse.command];
176        if (commandHandlerElement) {
177            commandHandlerElement(parse);
178            return;
179        }
180        if (!parse.sendId) {
181            parse.sendId = -1;
182        }
183        const isSelf = my && parse.sendId.toString() === my.id;
184        const isChat = getNOW_PAGE() === 'chat.html';
185        if (isChat) {
186            if (parse.recId === my_temp.id || parse.sendId === my_temp.id) {
187                switch (parse.command) {
188                    case "memory":
189                        // 回忆消息 不需要铃声
190                        addChatTextBlock(data_message, parse, parse.sendId.toString() === my.id);
191                        break;
192                    default:
193                        // 聊天
194                        Ring.playRing();
195                        addChatTextBlock(data_message, {
196                            id: parse.id,
197                            sendId: parse.sendId,
198                            sendDate: parse.sendDate,
199                            data: parse.data
200                        }, isSelf);
201                }
202            } else {
203                if (!isSelf) {
204                    Ring.playRing('dingDang')
205                    extractedMassage(parse);
206                }
207            }
208        } else if (!isSelf) {
209            Ring.playRing('dingDang')
210            extractedMassage(parse);
211        }
212    };
213
214    function reConnect() {
215        console.info("reConnectFun(webSocket)");
216        if (webSocket.readyState === WebSocket.OPEN) {
217            return;
218        }
219        const webSocket1 = new WebSocket(wsUrl);
220        initChatSocket(webSocket1, wsUrl, closeConnectFun, reConnectFun, checkConnect);
221        webSocket1.addEventListener("open", () => {
222            reConnectFun(webSocket1);
223        });
224    }
225
226    webSocket.onclose = function (event) {
227        console.log('链接被迫关闭:' + event.code);
228        if (closeConnectFun !== undefined) {
229            closeConnectFun(event.code);
230        }
231        // 假设状态码 1000 表示正常关闭,不重连
232        if (event.code !== 3024) {
233            setTimeout(() => reConnect(), 2000);
234        }
235    };
236}
237
238function checkSocketIsNotConnect(socket) {
239    return socket === null || socket === undefined || socket.readyState !== WebSocket.OPEN
240}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.