tim.js 7.37 KB
/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: limin
 * @Date: 2022-10-25 10:15:37
 * @LastEditors: limin
 * @LastEditTime: 2022-10-27 17:36:43
 * @FilePath: \scrm-wx-merchant-activity\src\components\TIM\im.js
 */
// 从v2.11.2起,SDK 支持了 WebSocket,推荐接入;v2.10.2及以下版本,使用 HTTP
import TIM from 'tim-wx-sdk'
import TIMUploadPlugin from 'tim-upload-plugin'
const TimOptions = {
  // SDKAppID: 1400743527
}
export default class IM {
  constructor(options = {}) {
    this.loginResolveRejectCache = []
    this.options = Object.assign({}, TimOptions, options)
    this.isSDKReady = false
    this.isLogin = false
    this.init()
    this.bindTIMEvent()
  }
  init() {
    // 创建 SDK 实例,`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
    this.tim = TIM.create({ SDKAppID: this.options.SDKAppID }) // SDK 实例通常用 tim 表示
    // 设置 SDK 日志输出级别,详细分级请参见 <a href="https://web.sdk.qcloud.com/im/doc/en/SDK.html#setLogLevel">setLogLevel 接口的说明</a>
    this.tim.setLogLevel(1) // 普通级别,日志量较多,接入时建议使用
    // tim.setLogLevel(1); // release 级别,SDK 输出关键信息,生产环境时建议使用
    // 注册腾讯云即时通信 IM 上传插件
    this.tim.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin })
  }

  /**
   * 绑定tim回调事件
   */
  bindTIMEvent() {
    this.tim.on(TIM.EVENT.SDK_READY, this.handleSDKReady, this)
    this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived, this)
    this.tim.on(TIM.EVENT.NET_STATE_CHANGE, this.onNetStateChange, this)
  }

  /**
   * 登录
   * @param {*} userID 用户唯一id
   * @param {*} userSig 生成签名
   * @returns
   */
  login(userID, userSig) {
    return new Promise((resolve, reject) => {
      if (!userID) {
        reject('userID is not be blank')
        return null
      }
      if (!userSig) {
        reject('userSig is not be blank')
        return null
      }
      this.tim
        .login({ userID, userSig })
        .then(() => {
          this.loginResolveRejectCache.push({ resolve, reject })
          this.isLogin = true
          return null
        })
        .catch(reject)
    })
  }
  /** 更新用户标配信息 
   * nick,avatar,gender,selfSignature,allowType
  */
  updateMyProfile(obj) {
    let promise = this.tim.updateMyProfile(obj);
    promise.then(function (imResponse) {
      console.log(imResponse.data); // 更新资料成功
    }).catch(function (imError) {
      console.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
    });
  }
  /**
   * 加入群聊
   * @returns Promise
   */
  joinGroup(groupID, type = TIM.TYPES.GRP_AVCHATROOM) {
    return new Promise((resolve, reject) => {
      this.options.groupID = groupID
      let promise = this.tim.joinGroup({ groupID, type })
      promise
        .then(function (imResponse) {
          switch (imResponse.data.status) {
            case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL: // Waiting to be approved by the admin
              console.info('Waiting to be approved by the admin') // Profile of the group
              resolve('Waiting to be approved by the admin')
              break
            case TIM.TYPES.JOIN_STATUS_SUCCESS: // Joined the group successfully
              console.info('Joined the group successfully') // Profile of the group
              resolve(imResponse.data.group)
              break
            case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // The user is already in the group
              console.info('The user is already in the group')
              resolve('The user is already in the group')
              break
            default:
              reject(imResponse.data.status)
              break
          }
        })
        .catch(function (imError) {
          console.warn('joinGroup error:', imError) // Error information
          reject('joinGroup error:' + imError)
        })
    })
  }
  quitGroup(groupID) {
    if (!groupID) {
      throw new Error('groupID is not be blank')
    }
    return this.tim.quitGroup(groupID)
  }
  /**
   * 登录并加入群聊
   * @param {*} param0
   * @returns
   */
  join({ userID, userSig, groupID }) {
    if (!userID) {
      throw new Error('userID is not be blank')
    }
    if (!userSig) {
      throw new Error('userSig is not be blank')
    }
    if (!groupID) {
      throw new Error('groupID is not be blank')
    }
    return this.login(userID, userSig).then(() => this.joinGroup(groupID))
  }
  /**
   * 退出群聊,并退出登录
   */
  quit() {
    return this.quitGroup(this.options.groupID).then(() => this.logout())
  }
  /**
   * 登出
   * @returns Promise
   */
  logout() {
    return new Promise((resolve, reject) => {
      this.tim
        .logout()
        .then(imResponse => {
          this.isSDKReady = false
          this.isLogin = false
          resolve(imResponse)
        })
        .catch(reject)
    })
  }

  /**
   * (内部)登录成功,且SDK Ready
   */
  handleSDKReady() {
    this.isSDKReady = true
    this.loginResolveRejectCache.forEach(({ resolve }) => {
      resolve({
        msg: '登录成功,且SDK Ready'
      })
    })
  }

  destroy() {
    return this.tim.destroy()
  }

  /**
   * 收到新消息回调
   * @param {*} event 回调消息体
   */
  onMessageReceived(event) {
    this.options.onMessageReceived(event.data)
  }

  /**
   * 网络波动回调
   * @param {*} event 回调消息体
   */
  onNetStateChange(event) {
    // v2.5.0 起支持
    // event.data.state 当前网络状态,枚举值及说明如下:
    // TIM.TYPES.NET_STATE_CONNECTED - 已接入网络
    // TIM.TYPES.NET_STATE_CONNECTING - 连接中。很可能遇到网络抖动,SDK 在重试。接入侧可根据此状态提示“当前网络不稳定”或“连接中”
    // TIM.TYPES.NET_STATE_DISCONNECTED - 未接入网络。接入侧可根据此状态提示“当前网络不可用”。SDK 仍会继续重试,若用户网络恢复,SDK 会自动同步消息
    let notify = {}
    switch (event.data.state) {
      case TIM.TYPES.NET_STATE_CONNECTED:
        notify = { message: '已接入网络', type: 'success' }
        break
      case TIM.TYPES.NET_STATE_CONNECTING:
        notify = { message: '连接中', type: 'warning' }
        break
      case TIM.TYPES.NET_STATE_DISCONNECTED:
        notify = { message: '当前网络不可用', type: 'danger' }
        break
      default:
        break
    }
    this.options.onNetStateChange(notify)
  }

  /**
   * 发送一条消息
   * @param {*} msg 消息内容
   * @returns Promise
   */
  send(msg) {
    return new Promise((resolve, reject) => {
      const message = this.createMessage(msg)
      this.sendMessage(message)
        .then(event => {
          this.onMessageReceived(Object.assign({}, event, { data: [event.data.message] }))
          resolve(event)
        })
        .catch(reject)
    })
  }

  /**
   * (内部)组装一条tim TEXT 消息体
   * @param {*} msg 消息内容
   * @returns 组装好的消息
   */
  createMessage(msg) {
    let message = this.tim.createTextAtMessage({
      to: this.options.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        text: msg
      }
    })
    return message
  }

  /**
   * (内部)发送一条消息
   * @param {*} message 组装好的tim消息内容
   * @returns Promise
   */
  sendMessage(message) {
    return this.tim.sendMessage(message)
  }
}