WXL (wul)
22 小时以前 1aaa2392eea4694076c6a329a5b88436ceb50194
src/utils/sipService-cs.js
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,201 @@
import JsSIP from "jssip";
class SipService {
  constructor() {
    this.ua = null;
    this.currentSession = null;
    this.onStatusChange = null; // çŠ¶æ€å˜åŒ–å›žè°ƒ
    this.onCallStatusChange = null; // æ–°å¢žé€šè¯çŠ¶æ€å›žè°ƒ
  }
  // åˆå§‹åŒ–SIP客户端
  init(config) {
    try {
      this.updateStatus("connecting", "连接中...");
console.log(config);
      this.ua = new JsSIP.UA({
        sockets: [new JsSIP.WebSocketInterface(config.wsUrl)],
        uri: config.sipUri,
        password: config.password,
        display_name: config.displayName,
        iceservers: [],
        // realm: config.realm,
        register: true,
        session_expires: 180,
        sessionTimersExpires: 300, // è®¾ç½® Session-Expires=120(必须 >= Min-SE)
        extraHeaders: [
          "Min-SE: 120", // å¯é€‰ï¼šæ˜¾å¼å‘Šè¯‰æœåŠ¡å™¨ä½ æ”¯æŒçš„æœ€å°å€¼
        ],
        register_expires: 300, // æ³¨å†Œæœ‰æ•ˆæœŸ(秒)
        connection_recovery_min_interval: 2, // æœ€å°é‡è¿žé—´éš”
        connection_recovery_max_interval: 30, // æœ€å¤§é‡è¿žé—´éš”
      });
      this.ua.start();
      // æ³¨å†Œäº‹ä»¶ç›‘听
      this.ua.on("registered", () => {
        this.updateStatus("registered", "已注册");
      });
      this.ua.on("registrationFailed", (e) => {
        this.updateStatus("failed", `注册失败: ${e.cause}`);
      });
      this.ua.on("disconnected", () => {
        this.updateStatus("disconnected", "连接断开");
      });
      this.ua.on("connected", () => {
        this.updateStatus("connecting", "重新连接中...");
      });
      // ç›‘听来电
      this.ua.on("newRTCSession", (data) => {
        this.handleIncomingCall(data.session);
      });
    } catch (error) {
      this.updateStatus("failed", `初始化失败: ${error.message}`);
      console.error("SIP初始化失败:", error);
    }
  }
  handleIncomingCall(session) {
    if (session.direction === "incoming") {
      console.log("来电:", session.remote_identity.uri.toString());
      // å¯ä»¥åœ¨è¿™é‡Œè§¦å‘ UI é€šçŸ¥
      if (this.onIncomingCall) {
        this.onIncomingCall(session);
      }
    }
  }
  // æ›´æ–°çŠ¶æ€å¹¶é€šçŸ¥UI
  updateStatus(type, text) {
    console.log(`SIP状态更新: ${type} - ${text}`);
    if (this.onStatusChange) {
      this.onStatusChange({ type, text });
    }
  }
  // ä¸€é”®æ‹¨å· - å¢žåŠ æ³¨å†ŒçŠ¶æ€æ£€æŸ¥
  makeCall(targetNumber) {
    if (!this.ua) {
      throw new Error("SIP客户端未初始化");
    }
    if (!this.ua.isRegistered()) {
      throw new Error("SIP未注册,无法呼叫");
    }
    const options = {
      sessionTimers: true,
      sessionTimersExpires: 300,
      extraHeaders: [
        "Min-SE: 120",
        "Route: <sip:@192.168.100.6>",
        "Accept: application/sdp",
        "Supported: replaces, timer",
        "Allow: INVITE, ACK, BYE, CANCEL, OPTIONS",
      ],
      eventHandlers: {
        progress: (e) => {
          this.updateCallStatus("calling", "呼叫中...");
        },
        failed: (e) => {
          this.updateCallStatus("ended", `呼叫失败: ${e.cause}`);
        },
        ended: (e) => {
          this.updateCallStatus("ended", "通话结束");
        },
        confirmed: (e) => {
          this.updateCallStatus("connected", "通话已接通");
        },
      },
      mediaConstraints: {
        audio: true,
        video: false,
      },
      rtcOfferConstraints: {
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 0,
        mandatory: {
          OfferToReceiveAudio: true,
          OfferToReceiveVideo: false,
        },
      },
      pcConfig: {
        iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
        iceTransportPolicy: "all",
        bundlePolicy: "balanced",
        rtcpMuxPolicy: "require",
        codecs: {
          audio: [
            { name: "PCMU", clockRate: 8000, payloadType: 0 },
            { name: "PCMA", clockRate: 8000, payloadType: 8 },
          ],
          video: [],
        },
      },
    };
    this.currentSession = this.ua.call(
      `sip:${targetNumber}@192.168.100.6`,
      options
    );
    // åœ¨ä¼šè¯åˆ›å»ºåŽä¿®æ”¹ SDP
    this.currentSession.on("peerconnection", (pc) => {
       this.updateCallStatus('calling', '呼叫中...');
      pc.createOffer = (offerOptions) => {
        return RTCPeerConnection.prototype.createOffer
          .call(pc, offerOptions)
          .then((offer) => {
            const modifiedSdp = offer.sdp
              .replace(/c=IN IP4 192\.168\.100\.10/g, "c=IN IP4 192.168.100.6")
              .replace(/m=audio \d+ RTP\/AVP.*/, "m=audio 7078 RTP/AVP 0 8");
            return new RTCSessionDescription({
              type: "offer",
              sdp: modifiedSdp,
            });
          });
      };
    });
    this.currentSession.on('failed', (e) => {
        this.updateCallStatus('failed', `呼叫失败2: ${e}`);
      });
      this.currentSession.on('ended', () => {
        this.updateCallStatus('ended', '通话已结束');
      });
      this.currentSession.on('confirmed', () => {
        this.updateCallStatus('connected', '通话已接通');
      });
    this.setupAudio(this.currentSession);
  }
  setupAudio(session) {
    session.connection.addEventListener("addstream", (e) => {
      const audioElement = document.getElementById("remoteAudio");
      if (audioElement) {
        audioElement.srcObject = e.stream;
      }
    });
  }
  // æŒ‚断当前通话
  endCall() {
  if (this.currentSession) {
      this.currentSession.terminate();
      this.updateCallStatus('ended', '通话已结束');
      this.currentSession = null;
    }
  }
  // æ–°å¢žæ–¹æ³•:更新通话状态
  updateCallStatus(type, text) {
    console.log(`通话状态更新: ${type} - ${text}`);
    if (this.onCallStatusChange) {
      this.onCallStatusChange({ type, text });
    }
  }
}
export default new SipService();