wangzhibo
4 天以前 10595d8632f959d0954d1939243196f4eed02372
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { defineStore } from "pinia";
// @ts-ignore
import io, { type Socket } from "@hyoga/uni-socket.io";
import type { Cs } from "../types";
import { useStore, module } from "/@/cool";
import { useSession } from "./session";
import { useMessage } from "./message";
 
export const useSocket = defineStore("cs.socket", () => {
    const config = module.config("cool-cs");
    const { user } = useStore();
    const session = useSession();
    const message = useMessage();
 
    let client = undefined as Socket | undefined;
 
    // 连接
    function connect() {
        if (!user.token) {
            return false;
        }
 
        if (client) {
            disconnect();
        }
 
        if (!client) {
            client = io(config.url, {
                transports: ["websocket", "polling"],
                auth: {
                    isAdmin: false,
                    token: user.token,
                },
            });
 
            client.on("connect", () => {
                console.log("[cs] connect");
            });
 
            client.on("disconnect", () => {
                console.log("[cs] disconnect");
            });
 
            client.on("msg", (data: Cs.Msg) => {
                if (data.type == 1) {
                    if (data.sessionId == session.info?.id) {
                        // 追加消息
                        message.append({
                            ...data.user,
                            ...data,
                            isAnimation: true,
                        });
 
                        // 读消息
                        message.read(data.id!);
                    }
                }
            });
        }
    }
 
    // 断开连接
    function disconnect() {
        client?.disconnect();
        client = undefined;
    }
 
    // 发送消息
    function send(content: Cs.Content) {
        if (client) {
            // 发送事件
            client.emit("send", {
                sessionId: session.info?.id,
                content,
            });
 
            // 追加消息
            message.append({ content });
        } else {
            console.log("[cs] client error");
        }
    }
 
    // 监听退出
    uni.$on("user.logout", () => {
        session.clear();
        message.clear();
        disconnect();
    });
 
    return {
        connect,
        client,
        send,
    };
});