# 定义这个全局状态管理

  1. 可以在注册页和main.ts 里应用 dxPeer.commit('initPeerJs',username)
import { createStore } from "vuex";
let peer = null;
let conn = null; // 返回文本对象
let current = null; // call 对象
let dataConnection = null; // 建立文本连接
export default createStore({
  state: {
    userName: "",
    TheActive: 0, // 通话的状态 0没有通话   1呼出  2.呼入 3.接通
    pitchOnNumber: null, //消息左侧选中
    ismsgopen: true, // 是否没有与会话连接
    TbleName: "",
    hangUpload: false, // 挂断按钮上的加载
    msg: {
      // 消息会话体
      destName: "", // 接收者账号
      fromName: "", // 发送者账号
      headPortrait: "", // 头像
      msgBody: "", // 消息
      userNickname: "", // 昵称
    },
  },
  mutations: {
    /**
     * 初始化 peer
     * @param state
     * @param userName  // 用户账号
     */
    initPeerJs(state, userName) {
      state.userName = userName;
      initFun(state, userName);
    },
    /**
     * 拨号
     * @param state
     * @param callName  // 呼叫用户账号
     */
    dialCall(state, callName) {
      callFun(state, callName);
    },
    // 接听
    async switchOn(state) {
      let stream = await getstream();
      if (!stream) {
        window.$message.errmsg("没有摄像头");
        return;
      }
      current.answer(stream); // 把流传给对方
      HandleTheCall(state, conn);
    },
    // 挂断电话
    CancelOn(state) {
      state.hangUpload = true;
      if (state.TheActive == 1) {
        quxiaofun(state);
        current.close();
        conn.send("quxaio");
      }
      if (state.TheActive == 2) {
        quxiaofun(state);
        conn.send("quxaio");
      }
      if (state.TheActive == 3) {
        current.close();
      }
    },
    // 挂断电话
    closeCall(state) {
      current.close();
    },
    //设置聊天框选中
    setIdx(state, num) {
      state.pitchOnNumber = num;
    },
    setMsg(state, data) {
      state.msg = data;
    },
    destroy(state) {
      peer.destroy();
    },
  },
});

const initFun = (state, userName) => {
  peer = new window.Peer(userName, {
    host: "duxinggj.com",
    port: 8089,
    path: "/dxPeer",
    config: {
      iceServers: [
        {
          urls: "stun:119.23.104.210:5349",
        },
        {
          urls: "turn:119.23.104.210:3478",
          username: "admin",
          credential: "kiss1001",
        },
      ],
      sdpSemantics: "unified-plan",
    },
  });
  peer.on("open", async (id) => {
    console.log("peerJs服务连接成功!我的账号是:" + id);
  });
  // 监听用户连接
  peer.on("connection", function (c) {
    conn = c;
    // conn.send("与用户" + c.id + "连接成功!");
    conn.on("data", function (data) {
      dataType(state, data);
    });
  });
  // 监听呼叫
  peer.on("call", async (call) => {
    current = call;
    state.TheActive = 2;
    state.TbleName = call.peer;
    const stream = await getstream();
    if (!stream) {
      quxiaofun(state);
      conn.send("NoCamera");
      return;
    }
    const myvideo: any = document.getElementById("CallingSideVideo");
    myvideo.srcObject = stream;
  });

  peer.on("close", function () {
    console.log("peer--close");
  });
  // 监听会话销毁了
  peer.on("destroy", function () {
    console.log("destroy");
  });
  /*监听会话销毁了 在这里可以做个断线重连*/
  peer.on("disconnected", function () {
    setTimeout(() => {
      peer.reconnect();
    }, 3000);
    console.log("disconnected");
  });

  // 会话错误信息钩子回调
  peer.on("error", function (e) {
    console.log("error", e);
    let str = "" + e;
    if (str.indexOf("Lost connection to server") >= 0) {
      // window.$message.error("连接视频服务失败");
      return;
    }
    if (str.indexOf("not connect") >= 0) {
      window.$message.error("对方可能没在线");
      return;
    }
    if (str.indexOf("is taken") >= 0) {
      //window.$message.error("检测此账号在其他的地方连接");
      return;
    }
  });
};

const callFun = async (state, callName) => {
  const stream = await getstream();
  if (!stream) {
    window.$message.error("无法与对方视频聊天,请检查摄像设备");
    return;
  }
  state.TheActive = 1;
  const myvideo: any = document.getElementById("CallingSideVideo");
  myvideo.srcObject = stream;
  let call = null;

  try {
    call = peer.call(callName, stream);
  } catch (e) {
    initFun(state, state.userName);
  }

  dataConnection = peer.connect(callName);
  dataConnection.on("open", function () {
    dataConnection.send("与用户" + state.userName + "连接成功!");
    dataConnection.on("data", function (data) {
      dataType(state, data);
    });
  });

  conn = dataConnection;
  current = call;
  console.log("呼叫对方:" + callName);
  HandleTheCall(state, dataConnection);
};

// 处理收到对方消息的处理类型
const dataType = (state, data) => {
  switch (data) {
    case "closecall":
      current.close();
      state.TheActive = 0;
      state.hangUpload = false;
      break;
    case "quxaio":
      quxiaofun(state);
      break;
    case "NoCamera":
      window.$message.error("呼叫失败:对方没有摄像头");
      quxiaofun(state);
      break;
  }
};
const quxiaofun = (state) => {
  state.TheActive = 0;
  state.hangUpload = false;
  const myvideo: any = document.getElementById("CallingSideVideo");
  myvideo.srcObject = null;
};
// 处理call事件
const HandleTheCall = (state, dataConnection) => {
  current.on("stream", (data) => {
    console.log("监听到了流call");
    console.log(data);
    state.TheActive = 3;
    const newsfriendvideo: any = document.getElementById("receivingEndVideo");
    newsfriendvideo.srcObject = data;
  });
  console.log(dataConnection);
  current.on("close", function (e) {
    console.log("监听呼叫--呼叫挂断了!");

    dataConnection.send("closecall");
  });
  current.on("error", function (err) {
    console.error("通话的状态异常了", err);
  });
  current.on("disconnect", function (err) {
    console.error("disconnect", err);
  });
};

const getstream = () => {
  return new Promise((resolve) => {
    var getUserMedia =
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia;
    getUserMedia(
      { video: true, audio: true },
      function (stream) {
        resolve(stream);
      },
      function (err) {
        resolve(false);
      }
    );
  });
};

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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257