融云相关代码5.1版本

这个是之前写比较老初版demo 后面在使用私有云的时候融云方面说不能用 但是测试是可以用的哈 所以整个代码就更换成最新的
如果只是应付项目演示用用还是没有问题
因为涉及上线才无奈换新的融云api

照例先贴出整个页面的代码 这个我封装成组件了 然后在最外层APP.vue页面引入
公有云和私有云的区别就是私有云有navi
基本傻瓜代码了 引入就可以用了

getLoginUserToken这个接口是我们为了方便维护没有每次都去融云获取token
而是后端专门写了一个接口 有一个获取token的页面 存储起来长期使用

具体前端也可以去调用融云官方的api自己封装一个接口去实时获取token用来测试
上一篇应该有写如果配置转发
不过如果是内网上线 还是要去后端转发来写接口的

在这里插入图片描述

<template>
  <div id="RongYun">
    <div class="rong-container">
      <!-- <h3 class="rong-title"> Web CallLib SDK Demo</h3> -->
      <div class="rong-action">
        <!-- <div  id='callee'>请等待在线 Demo 呼叫 ... </div> -->
        <div id='caller'>
          <span>当前登录用户:</span><span @click="DengL2"
                id='userId'></span><br />

          <div v-show="showpic">
            <div class="beonduty-flex ju-center">
              <div class="beonduty-img">
                <img :src="ToSrc">
              </div>
            </div>
            <div class="beonduty-flex ju-around">
              <div class="name">{{ToName}}</div>
              <div class="phone">{{targetIdvalue}}</div>
            </div>
          </div>

          <div>
            <!-- <input class="rong-input"
                   id="callUserId"
                   v-model="targetIdvalue"
                   type="text"
                   placeholder="被叫方用户 ID"
                   value=""
                   autocomplete="off"> -->

            <!-- <input id='call'
                   type="button"
                   value="发起通话"
                   @click="chaxunstatus()"> -->

            <div class="rong-flex"
                 v-show="showpic"
                 id='acceptID'>
              <div class="rong-btn rong-accept"
                   title="音频"
                   @click="chaxunstatus(1)"></div>
              <div class="rong-btn rong-video"
                   title="视频"
                   @click="chaxunstatus(2)"></div>
            </div>
          </div>

        </div>
      </div>
      <div class="rong-login-box">
        <div class="rong-video-box"></div>
        <div class="rong-input rong-btn rong-hungup rong-noshow"
             id='hunup'
             title="挂断"
             @click="hungup()"></div>
      </div>
      <!-- 来电的box -->
      <div class="rong-ringing"
           id='rong-ringing'>
        <div class="rong-flex">
          <div class="rong-btn rong-accept"
               title="接听"
               @click="accept()"></div>
          <div class="rong-btn rong-hungup"
               title="挂断"
               @click="hungup()"></div>
        </div>
      </div>
    </div>

  </div>
</template>
<script>

import {
  getLoginUserToken,
  getUserStatus
} from "@/api/floodControlDrainage/floodControlDrainage.js";

import { getUserInfo } from "@/api/system/user";


export default {
  name: "RongYun",
  props: {
    Getphone: {
      type: String,
      default: () => ""
    },
    ToName: {
      type: String,
      default: () => ""
    },
    ToSrc: {
      type: String,
      default: () => require("@/assets/images/siping-fangxun/User-icon.png")
    },
    RYtype: {
      type: String,
      default: () => ""
    },
    // getmediaType: {
    //   type: Number,
    //   default: () => 1
    // }
  },
  data () {
    return {
      getmediaType: 1,
      showpic: true,
      targetIdvalue: '',

      callMessage: '',
      currentUserId: '',
      rongCallLib: '',
      token: '',
      appkey: 'bmdehs6pb8ivs',
      navi: '',


      // appkey: 'pvxdm11bfioir',
      // navi: 'https://59.198.32.237:1444',

      userId: '',
      names: '',
      userNos: '',

      status: '',
    }
  },
  computed: {},
  methods: {
    // 获取用户信息
    GetuserInfo () {
      getUserInfo().then(res => {
        this.userinfo = res.data.data;
        console.log('this.userinfo', this.userinfo);
        this.userId = res.data.data.phone
        this.names = res.data.data.name
        this.userNos = res.data.data.account

        this.$nextTick(() => {
          this.DengL2()
        })

      });
    },

    DengL2 () {
      let params = {
        userNo: this.userNos,
        userName: this.names,
        phone: this.userId
      }

      getLoginUserToken(params).then(res => {
        if (res.data.code == 200) {
          console.log(res.data.data);
          this.token = res.data.data.token;

          if (res.data.data.token) {
            this.$nextTick(() => {
              this.connectIM()
            })
          }
        } else {
          let userUUIDNode = this.getDom('#userId');
          userUUIDNode.innerHTML = '登录失败,请点击此处重新登录';
        }

      }).catch(error => {
        let userUUIDNode = this.getDom('#userId');
        userUUIDNode.innerHTML = '登录失败,请点击此处重新登录';
      })
    },


    getDom (key) {
      return document.querySelector(key);
    },

    connectIM (e) {
      var prams = {
        Config: {
          appkey: this.appkey,
          navi: this.navi,
        },
        token: this.token,
      }

      this.initIM(prams).then((userId, rtcClient) => {

        console.log('rtcClient', rtcClient);
        console.log('userId', userId);

        this.currentUserId = userId.id;
        let userUUIDNode = this.getDom('#userId');
        userUUIDNode.innerHTML = userId.id;


        this.callInit(userId.rtc);
      });
    },


    initIM (params) {
      var appkey = params.Config.appkey;
      var navi = params.Config.navi;
      var token = params.token;
      RongIMClient.init(appkey, null, {
        navi
      });

      RongIMClient.setConnectionStatusListener({
        onChanged: function (status) {
          console.log('status changed', status);
          switch (status) {
            case RongIMLib.ConnectionStatus.CONNECTING:
              break;
            case RongIMLib.ConnectionStatus.DISCONNECTED:
              break;
            case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
            case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
              break;
          }
        }
      });

      RongIMClient.setOnReceiveMessageListener({
        onReceived: function (message) {
          console.log(message);
        }
      });
      return new Promise((resolve, reject) => {
        const rtcClient = RongIMClient.getInstance().install(RCRTC.installer);
        RongIMClient.getInstance().install(RongCallLib.installer)

        RongIMClient.connect(token, {
          onSuccess: function (userId) {
            var config = {
              im: RongIMClient.getInstance(),
              id: userId,
              rtc: rtcClient
            }
            resolve(config)
          },
          onTokenIncorrect: reject,
          onError: reject
        });
      });
    },

    callInit (rtcClient) {
      var that = this
      let config = {
        RongIMLib: RongIMLib,
        RongRTC: rtcClient,
        RongRTCAdapter: RCRTCAdapter,
        width: 640,
        height: 480,
        maxRate: 600,
        minRate: 50,
        frameRate: 15,
      };

      this.rongCallLib = RongCallLib.init(config);

      var videoWatcher = function (result) {
        console.log(result)
        let { type, isLocal } = result;
        const parentDom = document.querySelector('.rong-video-box');
        if (type === 'added') {
          let video = result.data;
          // video.muted = true;
          parentDom.appendChild(video);
          document.getElementById('hunup').classList.add('rong-show');
          document.getElementById('acceptID').classList.add('rong-noshow');
          if (isLocal) {
            console.log('we')
            // setTimeout(function () {
            //   that.rongCallLib.mute();
            // }, 500)

          }
        }
      };

      this.rongCallLib.videoWatch(videoWatcher);

      var commandWatcher = function (message) {
        console.log('message', message, that.commandEvents)
        that.callMessage = message
        that.commandEvents(message.messageType, message);
        // event && event(message);
      };
      this.rongCallLib.commandWatch(commandWatcher);
    },


    commandEvents (messageType, message) {
      console.log('messageType', messageType, message);
      switch (messageType) {
        case 'InviteMessage':
          this.InviteMessage(message)
          this.bus.$emit('openrongyuntype')
          break;
        case 'HungupMessage':
          this.HungupMessage(message)
          break;
        case 'SummaryMessage':
          if (this.RYtype == 'initiative') {
            this.showpic = true
          }
          this.SummaryMessage(message)
          break;
      }
    },


    InviteMessage (message) {
      this.callMessage = message;
      document.getElementById('rong-ringing').classList.add('rong-show');
      document.getElementById('acceptID').classList.add('rong-noshow');

      // NotificationComm('呼叫通知', { body: '收到呼叫等待您的接听' });
    },

    HungupMessage (message) {
      this.callMessage = message;
      this.hungup();
    },
    SummaryMessage () {
      document.getElementById('rong-ringing').classList.remove('rong-show');
      document.getElementById('acceptID').classList.remove('rong-noshow');
    },

    accept () {
      let params = this.messageToCallInfo(this.callMessage);
      this.rongCallLib.accept(params, function (error) {
        if (error) {
          console.error('接听通话失败', error);
        }
        document.getElementById('rong-ringing').classList.remove('rong-show');
        document.getElementById('acceptID').classList.remove('rong-noshow');

      });
    },

    hungup () {
      let params = this.messageToCallInfo(this.callMessage)
      var that = this
      this.rongCallLib.hungup(params, function (error) {
        if (error) {
          console.error('挂断通话失败', error);
        } else {

          document.getElementById('rong-ringing').classList.remove('rong-show');
          document.getElementById('acceptID').classList.remove('rong-noshow');


          document.getElementById('hunup').classList.remove('rong-show');
          const parentDom = document.querySelector('.rong-video-box');
          parentDom.innerHTML = '';
        }
      });
    },

    call () {
      console.log('getmediaType', this.getmediaType);
      let that = this
      let params = {
        conversationType: 1,
        targetId: this.targetIdvalue,
        inviteUserIds: [this.targetIdvalue],
        mediaType: this.getmediaType,
        extra: {
          name: 'test'
        }
      };
      this.callMessage = {
        conversationType: params.conversationType,
        targetId: params.targetId,
        content: {
          mediaType: params.mediaType
        }
      }
      this.rongCallLib.call(params, function (error) {
        if (error) {
          // console.error('发起通话失败', error);
          that.$message({
            type: "warning",
            message: '发起通话失败',
          });
        }
      });
    },

    // 查询当前用户是否在线
    async chaxunstatus (type) {
      this.getmediaType = type
      let prams = {
        phone: this.targetIdvalue
      }

      await getUserStatus(prams).then(res => {
        if (res.data.code == 200) {
          let data = JSON.parse(res.data.data)
          this.status = data.status == 1 ? true : false
          console.log('status', this.status);

          if (this.status) {
            this.call()
          } else {
            this.$message({
              type: "warning",
              message: '当前用户不在线!',
            });
          }

        }
      })
    },

    messageToCallInfo (message) {
      console.log('message', message);
      return {
        conversationType: message.conversationType,
        targetId: message.targetId,
        mediaType: message.content.mediaType,
        extra: {
          name: 'aaaa'
        }
      };
    },

  },
  // computed: {
  //   ...mapGetters([
  //     "userInfo",
  //   ]),
  // },
  watch: {
    // 便于调试 所以赋值方便可以修改电话
    Getphone: {
      handler (val) {
        if (val) {
          this.targetIdvalue = val
        }
      },
      immediate: true
    },
    // //控制判断是主动initiative打开 还是被动passivity呼叫打开
    //隐藏对应的图片
    RYtype: {
      handler (val) {
        if (val == 'initiative') {
          this.showpic = true
        } else {
          this.showpic = false
        }
      },
      immediate: true
    }
  },
  mounted () {
    // debugger
    this.GetuserInfo()
  },
  beforeDestroy () {
    // this.hungup()
  }
};
</script>
<style lang="less" scoped>
@import "./css/style.css";

#RongYun {
  width: 100%;
  height: 100%;
  font-size: 16px;
}

.rong-call input {
  color: #000 !important;
}

input:-internal-autofill-selected {
  -webkit-text-fill-color: #000 !important;
}
</style>

用v-show和bus操控显影 这样才能做到页面只初始化加载一次 而不报RTC重复加载的错误
下面是APP.VUE的bus相关 作为参考

<template>
  <div id="app"
       :class="[$route.fullPath=='/fxkhPage/index'?'activesssssssss':'']">
    <router-view />

    <!-- 融云的弹框 -->
    <div class="RYdia bg-every"
         v-show="rongyuntype">
      <div class="closeBtn"
           @click="rongyuntype=false">X</div>
      <RongYunPage :Getphone='GetFXphone'
                   :ToName='ToName'
                   :ToSrc='ToSrc'
                   :RYtype='RYtype'></RongYunPage>
    </div>

  </div>
</template>

<script>
import RongYunPage from '@/page/rongyun/index'  //融云子组件


export default {
  components: {
    RongYunPage
  },
  name: "app",
  data () {
    return {
      rongyuntype: false,
      GetFXphone: '',
      ToName: '',
      ToSrc: '',
      RYtype: 'initiative',  //控制判断是主动initiative打开 还是被动passivity呼叫打开
    };
  },
  created () {
  },
  mounted () {
    this.bus.$on('closeFX', data => {
      this.rongyuntype = false
    })

    this.bus.$on('openrongyuntype', data => {
      this.RYtype = 'passivity'
      this.rongyuntype = true
    })

    this.bus.$on('GetFXphone', data => {
      console.log(data);
      this.RYtype = 'initiative'
      this.GetFXphone = data.phone
      this.ToName = data.name
      this.ToSrc = data.src
      // this.getmediaType = Number(data.mediaType)

      this.$nextTick(() => {
        this.chaxunstatus()
      })

    })

    this.bus.$on((isOneMap) => {
      console.log(isOneMap, "isOneMap");
    });
    console.log(process.env);
  },
  beforeDestroy () {
    this.bus.$off('GetFXphone')
    this.bus.$off('closeFX')
    this.bus.$off('openrongyuntype')

  },

  methods: {
    chaxunstatus () {
      if (this.GetFXphone) {
        this.rongyuntype = true
      } else {
        this.$message({
          type: 'error',
          message: '无电话号码!',
        });
      }
    },
  },

这里是index.html引入部分 需要去融云管网下载对应的js 一般是需要官方提供账号密码才可以下载的哦

  <script src="./rongyun/RongCallLib.3.2.1.min.js" type="text/javascript"></script>
  <script src="./rongyun/RongIMLib-2.9.8-enterprise.2.prod.js" type="text/javascript"></script>
  <script src="./rongyun/RCRTC-5.1.latest.js" type="text/javascript"></script>
  <script src="./rongyun/RCRTC-5.1.0-enterprise.4.prod.js" type="text/javascript"></script>
  <script src="./rongyun/RCRTCAdapter-1.0.5.prod.js" type="text/javascript"></script>

最后就是传值调取这个弹框 然后点击调用最后的方法了

    // 调取融云服务
    torongyun (name, phone, src, mediaType) {
      let data = {
        phone: phone ? phone : '13455556666',
        name: name ? name : '默认姓名',
        src: src,
      }
      this.bus.$emit('GetFXphone', data)
    },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值