rtc.vue 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. <template>
  2. <div align="center" class="rtc-page cover-bg" :style="{height: pageData.height + 'px'}">
  3. <!-- video 容器 -->
  4. <div class="video-wrapper" id="videoRef" :style="{width: pageData.videoWidth + 'px', height: pageData.videoHeight + 'px'}"></div>
  5. <!-- 三menu键 -->
  6. <div id="foot-menu-wrap" :style="`height: ${pageData.footMenuHeight}px`">
  7. <div @click.stop="sendKey(187)"><van-icon name="wap-nav" size="24px"/></div>
  8. <div @click.stop="sendKey(3)"><van-icon name="wap-home-o" size="24px"/></div>
  9. <div @click.stop="sendKey(4)"><van-icon name="arrow-left" size="24px"/></div>
  10. </div>
  11. <!-- 悬浮按钮 -->
  12. <FloatBtn :width="pageData.width" :height="pageData.height" :latency="rtcNetwork.currentRoundTripTime" @onClick="levitatedSphereVisible = true"/>
  13. <!-- 左侧popup -->
  14. <LeftMenuPopup
  15. ref="leftMenuPopupRef"
  16. :engine="engine"
  17. :userCardId="activeCloud.userCardId"
  18. :levitatedSphereVisible.sync="levitatedSphereVisible"
  19. :latency="rtcNetwork.currentRoundTripTime"
  20. :groupList="groupList"
  21. :cloudList="cloudList"
  22. :mealTypeObj="mealTypeObj"
  23. :imgFun="imgFun"
  24. @funcHandle="funcHandle"
  25. @changeCloud="changeCloudHandle"
  26. @exit="exit"
  27. />
  28. <!-- 右侧popup -->
  29. <!-- <RightPopup ref="rightPopupRef" :engine="engine" :userCardId="activeCloud.userCardId" :levitatedSphereVisible.sync="levitatedSphereVisible" @shearplate="shearplate" @exit="exit"/> -->
  30. <!-- 输入并复制到粘贴板 -->
  31. <InputCopy ref="inputCopyRef" @openPasteboard="openPasteboard"/>
  32. <!-- 云机内部的粘贴板内容 -->
  33. <CloudPhoneClipboard ref="cloudPhoneClipboardRef"/>
  34. <!-- 超时无操作 -->
  35. <TimeoutNoOps ref="timeoutNoOpsRef" />
  36. <!-- 计时卡计时 | 计费规则 | 应用推荐 -->
  37. <TimeBalance ref="timeBalanceRef" :parametersData="parametersData" :userCardId="activeCloud.userCardId" :userCardType="parametersData.userCardType" @downline="$refs.rightPopupRef.downline()"/>
  38. </div>
  39. </template>
  40. <script>
  41. import meta from './config/meta.js';
  42. import request from './config/request.js';
  43. import logReport from './config/logReport.js';
  44. import publicMixin from './mixins/public.js';
  45. import * as uni from '../../static/static/js/uni.webview.1.5.2.js';
  46. import FloatBtn from './components/FloatBtn.vue';
  47. import RightPopup from './components/RightPopup.vue';
  48. import LeftMenuPopup from './components/LeftMenuPopup.vue';
  49. import InputCopy from './components/InputCopy.vue';
  50. import CloudPhoneClipboard from './components/CloudPhoneClipboard.vue';
  51. import TimeoutNoOps from './components/TimeoutNoOps.vue';
  52. import TimeBalance from './components/TimeBalance.vue';
  53. /**
  54. * @description: 判断当前页面运行环境
  55. * @return {Object} 返回当前页面运行环境
  56. */
  57. const isBrowserEnvironment = function() {
  58. // 判断是否在浏览器环境中
  59. const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined';
  60. // 判断是否在微信环境中
  61. const isWechat = /MicroMessenger/i.test(navigator.userAgent);
  62. // 判断是否在微信小程序的 web-view 中
  63. const isMiniProgramWebview = isWechat && /miniProgram/i.test(navigator.userAgent);
  64. // 判断是否是 iPhone 设备
  65. const isIPhone = /iPhone/i.test(navigator.userAgent);
  66. // 判断是否是顶级窗口(不是嵌套在 iframe 中)目前只有ios的浏览器中才会是顶级窗口
  67. const isTopWindow = window.parent === window.self;
  68. return {
  69. isBrowser, // 是否在浏览器环境中
  70. isWechat, // 是否在微信环境中
  71. isMiniProgramWebview, // 是否在微信小程序的 web-view 中
  72. isIPhone, // 是否是 iPhone 设备
  73. isTopWindow, // 是否是顶级窗口
  74. };
  75. }
  76. export default {
  77. auth: false,
  78. name: 'webRTC',
  79. layout: 'cloudPhone',
  80. components: {
  81. FloatBtn,
  82. RightPopup,
  83. InputCopy,
  84. CloudPhoneClipboard,
  85. TimeoutNoOps,
  86. TimeBalance,
  87. LeftMenuPopup,
  88. },
  89. head() {
  90. return {
  91. title: '云手机',
  92. meta: [ ...meta ],
  93. script: [
  94. {
  95. // ./ 路径指向nuxt.config.js同级目录的static文件夹
  96. src: './rtcEngine/config/js/SDK.min.js', // sdk 2.0文件
  97. type: 'text/javascript',
  98. async: false,
  99. defer: false,
  100. onload: '$_script_loadHandler()', // 加载成功回调created生命周期中定义的方法
  101. onerror: '$_script_errHandler()', // 加载失败回调created生命周期中定义的方法
  102. },
  103. // {
  104. // // ./ 路径指向nuxt.config.js同级目录的static文件夹
  105. // src: './static/js/uni.webview.1.5.2.js', // uniapp webview 1.5.2文件
  106. // type: 'text/javascript',
  107. // async: true,
  108. // defer: false,
  109. // onload: '$_script_uni_loadHandler()', // 加载成功回调created生命周期中定义的方法
  110. // }
  111. ]
  112. }
  113. },
  114. mixins: [publicMixin],
  115. data() {
  116. return {
  117. // 日志上报实例
  118. logReportObj: null,
  119. // SDK加载状态
  120. sdkLoadStatus: 'loading', // sdk 加载状态 [loading|success|error]
  121. // 页面数据
  122. pageData: {
  123. width: 0, // 页面宽度
  124. height: 0, // 页面高度
  125. footMenuHeight: 40, // 底部菜单高度
  126. videoWidth: 0, // 视频宽度
  127. videoHeight: 0, // 视频高度
  128. },
  129. // 是否支持webRTC
  130. isSupportRtc: !!(
  131. typeof RTCPeerConnection !== 'undefined' &&
  132. typeof RTCIceCandidate !== 'undefined' &&
  133. typeof RTCSessionDescription !== 'undefined'
  134. ),
  135. // url 问号后的参数
  136. parametersData: {
  137. /**
  138. * @description: 传递的参数
  139. * @param {String} record 数据id
  140. * @param {Number} userCardId 必传 云机的id
  141. * @param {String} mealType 云机套餐类型 eg: VIP、STARBALL...
  142. * @param {Number} sourceType 云机来源: 0:购买 1试用 2:免费激活码 3:免费活动抽奖 4:ar app注册 5:9.9元套餐年卡 ',
  143. * @param {Number} userCardType 必传 云机的类型 0 普通套餐 1、2、3:年卡、普通计时、自动续费普通计时
  144. * @param {Number} validTime 卡的有效期
  145. * @param {String} rm 卡所在的机房
  146. * @param {Number} isShowCountdown 是否显示倒计时 0:否 1:是
  147. * @param {Number} isShowRule 是否显示规则 0:否 1:是
  148. * @param {Number} timingStatus 卡的计时状态 0:停止计时 1:开始计时 2:待确认开始计时"
  149. * @param {String} isFirstConnect 是否是首次连接
  150. * @param {Number} authPhone 0自身购买的云手机 1获取得到的云手机
  151. * @param {String} username 用户名
  152. * @param {String} token 必传 token
  153. * @param {Number} isTips 必传 是否显示提示 0:否 1:是
  154. * @param {Number} isWeixin 必传 是否是微信小程序环境 0:否 1:是
  155. * @param {String} merchantSign 必传 商户标识
  156. */
  157. },
  158. // 当前使用的云机数据
  159. activeCloud: {},
  160. // 卡的连接信息
  161. connectData: {},
  162. // 云手机引擎 播放器实例
  163. engine: {},
  164. // webRtc网络分析数据
  165. rtcNetwork: {
  166. currentRoundTripTime: 0, // 当前往返时间(网络延迟)
  167. },
  168. doConnectDirectivesWs: null, // 云手机指令通道
  169. doConnectDirectivesIntervalerPing: null, // 业务通道定时标识 云手机指令通道心跳
  170. doConnectDirectivesRequestNum: 1, // 业务通道重连次数
  171. doConnectDirectivesRequestNumMax: 6, // 业务通道重连次数上限
  172. // 右侧popup显隐
  173. levitatedSphereVisible: false,
  174. }
  175. },
  176. // 页面初始化后触发
  177. async fetch() {
  178. // 获取页面传递参数
  179. this.parametersData = this.$route.query;
  180. // 获取用户所有云机列表
  181. await this.getCloudList();
  182. // 获取当前云机信息
  183. this.activeCloud = this.cloudList.find(item => item.userCardId === +this.parametersData.userCardId) ?? {};
  184. // 获取所有云机套餐信息
  185. await this.getMealIconInfo();
  186. // 获取云机分组
  187. await this.getCloudGroupId();
  188. if(this.sdkLoadStatus === 'success') {
  189. // 开始运行程序
  190. if(Object.keys(this.activeCloud).length) {
  191. this.start(this.activeCloud);
  192. }else {
  193. this.$toast('云手机不存在');
  194. }
  195. }else {
  196. console.log('SDK加载失败');
  197. this.$toast('加载失败');
  198. }
  199. },
  200. computed: {
  201. // 是否为微信浏览器环境
  202. isWeChatBrowser() {
  203. return this.$userAgent.isWx;
  204. },
  205. },
  206. created() {
  207. // 设置html标签的背景为黑色
  208. document.body.style.background = '#000';
  209. // 定义全局变量 用于监听sdk加载状态
  210. window.$_script_loadHandler = async ()=> {
  211. console.log('$_script_loadHandler: SDK加载成功');
  212. this.sdkLoadStatus = 'success';
  213. };
  214. window.$_script_errHandler = ()=> {
  215. console.log('SDK加载失败');
  216. this.sdkLoadStatus = 'error';
  217. }
  218. },
  219. mounted() {
  220. // 获取窗口尺寸
  221. this.getInitSize();
  222. window.onresize = () => {
  223. console.log('窗口尺寸变化');
  224. this.getInitSize()
  225. };
  226. // 初始化页面监听事件
  227. this.initListener();
  228. },
  229. // 页面销毁前触发
  230. beforeDestroy() {
  231. // 关闭通道
  232. this.closeChannel();
  233. // 销毁页面监听事件
  234. this.destroyListener();
  235. },
  236. methods: {
  237. // 初始化页面监听事件
  238. initListener() {
  239. // 禁止双击缩放
  240. document.addEventListener('dblclick', this.preventDefault);
  241. // 添加监听 页面显示或隐藏 事件
  242. document.addEventListener('visibilitychange', this.visibilitychanged);
  243. },
  244. // 销毁页面监听事件
  245. destroyListener() {
  246. // 允许双击缩放
  247. document.removeEventListener('dblclick', this.preventDefault);
  248. // 移除监听 页面显示或隐藏 事件
  249. document.removeEventListener('visibilitychange', this.visibilitychanged);
  250. },
  251. // 阻止默认事件
  252. preventDefault(e) {
  253. e.preventDefault();
  254. },
  255. // 监听 页面显示或隐藏 执行的函数
  256. visibilitychanged() {
  257. // 获取当前环境
  258. const env = isBrowserEnvironment();
  259. // 获取当前页面的可见性状态
  260. const visibilityState = document.visibilityState;
  261. if (visibilityState === 'visible') {
  262. // 页面显示时的逻辑
  263. // 网页重载
  264. if (env.isBrowser && env.isTopWindow && env.isIPhone) {
  265. location.reload();
  266. }
  267. } else if (visibilityState === 'hidden') {
  268. // 页面隐藏时的逻辑
  269. // video.pause();
  270. } else if (visibilityState === 'prerender') {
  271. // 页面预渲染时的逻辑
  272. console.log('页面处于预渲染状态');
  273. } else if (visibilityState === 'unloaded') {
  274. // 页面即将卸载时的逻辑 移除监听
  275. document.removeEventListener('visibilitychange', this.visibilitychanged);
  276. }
  277. },
  278. // 获取初始化尺寸
  279. getInitSize() {
  280. // 获取窗口尺寸
  281. this.pageData.height = window.innerHeight;
  282. this.pageData.width = window.innerWidth;
  283. // 计算视频尺寸 webRTC需要做成16:9的画面
  284. let videoWidth = this.pageData.width;
  285. let videoHeight = this.pageData.height - this.pageData.footMenuHeight;
  286. // 计算当前视口的宽高比
  287. const currentRatio = videoWidth / videoHeight;
  288. console.log(`当前视口的宽高比: ${currentRatio}`);
  289. // 9:16 的目标比例
  290. const targetRatio = 9 / 16;
  291. // 判断当前视口的宽高比与目标比例的关系
  292. if (currentRatio > targetRatio) {
  293. // 当前视口的宽高比大于目标比例,说明宽度“过宽”,需要以高度为基准
  294. console.log("当前视口宽度过宽,应以高度为基准调整宽度");
  295. this.pageData.videoWidth = videoHeight * targetRatio;
  296. this.pageData.videoHeight = videoHeight;
  297. console.log(`1目标: 宽${this.pageData.videoWidth},高${this.pageData.videoHeight}`);
  298. } else {
  299. // 当前视口的宽高比小于目标比例,说明高度“过高”,需要以宽度为基准
  300. console.log("当前视口高度过高,应以宽度为基准调整高度");
  301. this.pageData.videoWidth = videoWidth;
  302. this.pageData.videoHeight = videoWidth / targetRatio;
  303. console.log(`2目标: 宽${this.pageData.videoWidth},高${this.pageData.videoHeight}`);
  304. }
  305. },
  306. // 获取卡的信息
  307. async getConnectData({isWeixin, merchantSign}) {
  308. let userCardId = this.activeCloud.userCardId;
  309. try {
  310. // 设置上报参数
  311. this.logReportObj.setParams({userCardId});
  312. let isWx = this.$userAgent.isWx;
  313. let clientType = (+isWeixin || isWx) ? 'wx' : undefined;
  314. // 设置上报参数
  315. this.logReportObj.setParams({userCardId});
  316. clientType && this.logReportObj.setParams({clientType});
  317. const res = await this.$axios.$post('/resources/user/cloud/connect', { userCardId }, {
  318. headers: {
  319. merchantSign,
  320. },
  321. });
  322. if (!res.success) {
  323. // 设置日志 推流状态为失败,和链接状态
  324. this.logReportObj.setParams({plugFowStatus: 2, linkWay: this.logReportObj.RESPONSE_CODE[res.status] || 0, linkEndTime: this.logReportObj.formatDate(new Date())});
  325. // 日志上报
  326. this.logReportObj.collectLog(
  327. `接口获取数据失败:
  328. url: /api/resources/user/cloud/connect
  329. method: post
  330. 参数: ${JSON.stringify({ userCardId })}
  331. 响应: ${JSON.stringify(res)}`
  332. );
  333. // res.status状态码枚举值 0: 正常
  334. const statusEnum = {
  335. // 5200:RBD资源挂载中
  336. 5200: '网络异常,请稍后重试',
  337. // 入使用排队9.9,年卡
  338. 5220: '云手机正在一键修复中',
  339. 5203: '正在排队中,请稍等',
  340. // 9.9年卡连接异常,重新进入排队
  341. 5204: '云机异常,正在为你重新分配云机',
  342. 5228: '卡的网络状态为差',
  343. 5229: '接口返回链接信息缺失',
  344. };
  345. // NOTE 这里可设置重连机制, 重连次数上限6次, 每次重连间隔3秒, 暂不做重连
  346. // 提示错误信息
  347. this.$toast(statusEnum[res.status] || '网络异常,请稍后重试');
  348. return Promise.reject(new Error(statusEnum[res.status] || '网络异常,请稍后重试'));
  349. }
  350. return res.data;
  351. }catch (error) {
  352. // 设置上报参数
  353. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  354. // 日志上报
  355. this.logReportObj.collectLog(
  356. `接口获取数据失败:
  357. url: /api/resources/user/cloud/connect
  358. method: post
  359. 参数: ${JSON.stringify({ userCardId })}
  360. 响应: ${JSON.stringify(error)}`
  361. );
  362. console.log('error connectAxios:', error);
  363. return Promise.reject(error);
  364. }
  365. },
  366. // 判断卡的连接方式
  367. async judgeConnectType(cardData) {
  368. try {
  369. // 设置上报参数
  370. this.logReportObj.setParams({videoType: cardData.videoCode.toLowerCase(), resourceId: cardData.resourceId});
  371. // 不支持webRTC跳转到指定的页面进行拉流
  372. if (!cardData.isWebrtc) {
  373. // 关闭日志上报
  374. this.logReportObj?.destroy();
  375. // 跳转指定页面
  376. location.replace(`${location.origin}/h5/webRtcYJ/WXtrialInterface.html${location.search}`)
  377. return Promise.reject();
  378. }
  379. // 是否支持webRTC
  380. if (!this.isSupportRtc) {
  381. // 设置日志 推流状态为失败
  382. this.logReportObj.setParams({plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  383. // 日志上报
  384. this.logReportObj.collectLog(`${+this.parametersData.isWeixin ? '微信小程序' : ''}当前版本暂不支持使用`);
  385. this.$dialog.alert({
  386. title: '提示',
  387. message: '当前环境不支持使用,可下载谷歌浏览器或客户端进行使用',
  388. confirmButtonText: '确定',
  389. confirmButtonColor: '#3cc51f',
  390. callback: (_, done) => {
  391. done();
  392. this.exit();
  393. }
  394. })
  395. return Promise.reject(new Error('当前浏览器不支持webRTC'));
  396. }
  397. // webRtc连接,需获取连接中转地址
  398. if (cardData.webrtcNetworkAnalysis) {
  399. // 如果有网络分析的请求地址, 则请求,否则失败
  400. const { data: webrtcNetworkAnalysisReq }= await request.get(cardData.webrtcNetworkAnalysis); // 这个接口单独使用axios请求, 因为返回的数据跟封装的数据结构不一统一,是其他平台的接口,所以单独请求
  401. if (webrtcNetworkAnalysisReq !== null && webrtcNetworkAnalysisReq.success && webrtcNetworkAnalysisReq.data) {
  402. // 保存获取的连接地址到connect的请求的响应中, 方便后面使用
  403. cardData.webrtcNetwork = webrtcNetworkAnalysisReq.data;
  404. // 设置上报参数
  405. this.logReportObj.setParams({transferServerIp: webrtcNetworkAnalysisReq.data});
  406. return cardData;
  407. }else{
  408. // 设置上报参数
  409. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  410. // 日志上报
  411. this.logReportObj.collectLog(
  412. `webRtc连接,获取中转地址失败:
  413. url: ${cardData.webrtcNetworkAnalysis}
  414. method: get
  415. 参数: 无
  416. 响应: ${JSON.stringify(webrtcNetworkAnalysisReq)}`
  417. );
  418. // 弹窗并退出
  419. this.$dialog.alert({
  420. title: '提示',
  421. message: '访问失败,请稍后重试',
  422. confirmButtonText: '确定',
  423. confirmButtonColor: '#3cc51f',
  424. beforeClose: (action, done) => {
  425. done()
  426. this.exit();
  427. }
  428. })
  429. return Promise.reject(new Error('网络分析请求失败'));
  430. }
  431. }else{
  432. // 设置上报参数
  433. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2});
  434. // 日志上报
  435. this.logReportObj.collectLog(
  436. `webRtc连接,获取请求中转地址为空:
  437. url: /api/resources/user/cloud/connect
  438. method: post
  439. 参数: ${JSON.stringify({ userCardId: this.activeCloud.userCardId })}
  440. 响应: ${JSON.stringify(res)}`
  441. );
  442. return Promise.reject(new Error('网络分析请求地址不存在'));
  443. }
  444. } catch (error) {
  445. console.log('判断卡的连接方式', error);
  446. return Promise.reject(error);
  447. }
  448. },
  449. // 初始化webRTC及相关配置
  450. initWebRtc() {
  451. try {
  452. // 获取挂载的容器元素
  453. const videoRef = document.getElementById("videoRef");
  454. // 解构connectData中的数据
  455. const { sn: topic, cardToken: authToken, localIp, internetHttps, internetHttp, webrtcNetwork, webrtcTransferCmnet, webrtcTransferTelecom, webrtcTransferUnicom, videoCode } = this.connectData;
  456. // 判断长连接的协议方式
  457. const isWss = location.protocol === 'https:';
  458. // 生成连接地址
  459. const url = `${isWss ? 'wss://' : 'ws://'}${isWss ? internetHttps : internetHttp}/nats`;
  460. let quality = localStorage.getItem('definitionValue') ?? '自动';
  461. // 统一使用三网解析地址
  462. const ICEServerUrl = [
  463. { "CMNET": webrtcNetwork }, // 移动
  464. { 'CHINANET-GD': webrtcNetwork }, // 电信
  465. { 'UNICOM-GD': webrtcNetwork }, // 联通
  466. ];
  467. // 配置连接参数
  468. const connection = {
  469. mount: videoRef,
  470. displaySize: { // 视频在页面显示的尺寸 必填
  471. width: this.pageData.videoWidth,
  472. height: this.pageData.videoHeight,
  473. },
  474. topic, // SN号 必填
  475. url, //信令服务地址 必填
  476. ICEServerUrl,
  477. forwardServerAddress: '', // 转发服务器地址
  478. ip: localIp, // 实例ip
  479. controlToken: '', // 控制token
  480. width: 720, // 推流视频宽度 必填
  481. height: 1080, // 推流视频高度 必填
  482. cardWidth: 0, // 云机系统分辨率 宽 必填
  483. cardHeight: 0, // 云机系统分辨率 高 必填
  484. cardDensity: 0, // 云机系统显示 密度 必填
  485. authToken, //拉流鉴权 token 必填
  486. quality, // 画质(码率) 超清 | 高清 | 标清 | 流畅
  487. fps: 30, //必填
  488. videoCodec: videoCode, // 视频编码格式 必填
  489. videoCodecMethod: true, // 硬编true | 软编false
  490. isMuted: false, // 是否静音
  491. isAllowedOpenCamera: true, // 是否允许打开摄像头
  492. sendFollow: true, // 是否允许主控转发文本到实例
  493. callback: (event)=> {console.log('webRTC回调', event);}
  494. };
  495. // 设置日志参数 推流质量
  496. this.logReportObj.setParams({imageQuality: quality});
  497. // 获取SDK类
  498. const MediaSdk = window.rtc_sdk.MediaSdk;
  499. // 初始化 SDK
  500. this.engine = new MediaSdk();
  501. console.log('RtcEngineConfig==', connection)
  502. // 初始化 SDK 并传入连接参数
  503. this.engine.RtcEngine(connection);
  504. // 监听回调方法
  505. this.eventCallbackFunction();
  506. } catch (error) {
  507. console.log('webRTC初始化失败', error);
  508. }
  509. },
  510. // webRTC状态回调监听回调方法
  511. eventCallbackFunction() {
  512. const engine = this.engine;
  513. // 连接成功
  514. engine.on('CONNECT_SUCCESS', (r) => {
  515. console.log("webrtc连接成功====★★★★★", r);
  516. if (r.code === 1005) { // 1005: 拉流鉴权成功
  517. // 清除loading
  518. this.$toast.clear();
  519. // 设置日志 推流状态为成功
  520. let now = new Date();
  521. this.logReportObj.setParams({plugFowStatus: 1, linkWay: 1, timeConsuming: now.getTime() - this.logReportObj.timeStartTime, linkEndTime: this.logReportObj.formatDate(now)});
  522. // 日志上报
  523. this.logReportObj.collectLog(`拉流成功`);
  524. // 初始化业务指令通道
  525. this.initControlChannel();
  526. // 查询超过指定触碰时间是否提示关闭弹窗
  527. this.$refs.timeoutNoOpsRef.pushflowPopup();
  528. // 获取云机剩余时长
  529. this.$refs.timeBalanceRef.getResidueTime();
  530. }
  531. });
  532. // 连接关闭
  533. engine.on('CONNECT_CLOSE', (r) => {
  534. console.log("webrtc关闭====★★★★★", r);
  535. });
  536. // 网络连接统计信息监听
  537. engine.on('NETWORK_STATS', (r) => {
  538. console.log("webrtc网络连接统计信息监听====★★★★★", r);
  539. this.rtcNetwork = r;
  540. });
  541. // 连接异常
  542. engine.on('CONNECT_ERROR', (r) => {
  543. console.log("webrtc异常状态====★★★★★", r);
  544. // 异常状态枚举值
  545. const statusEnum = {
  546. 10011: '连接超时',
  547. 10012: '连接失败',
  548. 1002: 'rtc连接失败',
  549. 1003: 'rtc异常断开',
  550. 1004: 'rtc连接失败',
  551. 1006: '鉴权失败',
  552. };
  553. // 设置日志 推流状态为失败
  554. this.logReportObj.setParams({plugFowStatus: 2, linkWay: 0, linkEndTime: this.logReportObj.formatDate(new Date())});
  555. // 日志上报
  556. this.logReportObj.collectLog( `${statusEnum[r.code] || '连接异常'}: 消息: ${JSON.stringify(r)}` );
  557. this.$dialog.alert({
  558. title: '提示',
  559. message: '链接超时',
  560. confirmButtonText: '确定',
  561. confirmButtonColor: '#3cc51f',
  562. beforeClose: (action, done) => {
  563. done()
  564. this.exit()
  565. }
  566. })
  567. });
  568. // 显示区域大小发生改变 响应
  569. engine.on('RECEIVE_RESOLUTION', (r) => {
  570. // 分辨率大小发生改变,响应
  571. console.log("分辨率大小发生改变,响应 => RECEIVE_RESOLUTION", r);
  572. });
  573. },
  574. // 业务指令通道初始化
  575. initControlChannel() {
  576. try {
  577. // 初始化业务指令通道
  578. let { internetHttps, internetHttp, localIp, cardToken } = this.connectData;
  579. const isWss = location.protocol === 'https:';
  580. let cUrl = `${isWss ? 'wss' : 'ws'}://${isWss ? internetHttps : internetHttp}/businessChannel?cardIp=${localIp}&token=${cardToken}&type=directives`;
  581. this.doConnectDirectivesWs = new WebSocket(cUrl);
  582. this.doConnectDirectivesWs.binaryType = 'arraybuffer';
  583. // 清除定时器
  584. if (this.doConnectDirectivesIntervalerPing) {
  585. clearInterval(this.doConnectDirectivesIntervalerPing);
  586. }
  587. // 链接成功
  588. this.doConnectDirectivesWs.onopen = (e) => {
  589. // 日志上报
  590. this.logReportObj.collectLog( `消息: 业务通道连接成功` );
  591. // 重置重连次数
  592. this.doConnectDirectivesRequestNum = 1;
  593. // 设置定时器 每3秒发送一次心跳
  594. this.doConnectDirectivesIntervalerPing = setInterval(() => {
  595. if (this.doConnectDirectivesWs.readyState === 1) {
  596. this.sendWsCommand({ type: 'ping' });
  597. } else {
  598. clearInterval(this.doConnectDirectivesIntervalerPing);
  599. }
  600. }, 3000);
  601. // 输入法: 本地输入法 1 云机输入法 2
  602. this.sendWsCommand({ type: 'InputMethod', data: { type: 2 } });
  603. }
  604. // 接受到的消息
  605. this.doConnectDirectivesWs.onmessage = res => {
  606. const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
  607. switch (result.type) {
  608. case 'reProduceText':
  609. this.$native.clipboard.writeText(result.data.text);
  610. break
  611. case 'downAdnInstallRep':
  612. this.$toast(result.data.msg)
  613. break
  614. // 接受到这个消息就自动退出云机
  615. case 'exitPhone':
  616. this.exit();
  617. break
  618. }
  619. }
  620. // 链接报错的回调
  621. this.doConnectDirectivesWs.onerror = res => {
  622. // 设置日志
  623. this.logReportObj.setParams({plugFowStatus: 1, linkWay: 0, linkEndTime: this.logReportObj.formatDate(new Date())});
  624. // 日志上报
  625. this.logReportObj.collectLog(
  626. `业务指令通道报错:
  627. url: ${res.target.url}
  628. type: ${res.type}
  629. 消息: ${JSON.stringify(res)}`
  630. );
  631. if (this.doConnectDirectivesRequestNum > this.doConnectDirectivesRequestNumMax) {
  632. return this.exit();
  633. }else{
  634. // 重连次数加1
  635. ++this.doConnectDirectivesRequestNum;
  636. // 重连
  637. this.initControlChannel();
  638. }
  639. }
  640. } catch (error) {
  641. console.log('initControlChannel error', error);
  642. }
  643. },
  644. /**
  645. * popup 功能按钮点击事件
  646. * @param {Object} val 传递的参数
  647. * @description 传递的参数格式: { code: 'hideKey', label: '隐藏虚拟键', icon: 'icon-hide' }
  648. */
  649. funcHandle({code}) {
  650. console.log('funcHandle code:', code);
  651. switch (code) {
  652. case 'hideKey':
  653. // 隐藏虚拟按键
  654. document.getElementById('foot-menu-wrap').style.display = 'none';
  655. this.pageData.footMenuHeight = 0; // 设置底部菜单高度为0
  656. this.getInitSize(); // 重新计算视频尺寸
  657. this.changeVideoStyle(); // 重新设置视频尺寸
  658. break;
  659. case 'showKey':
  660. // 显示虚拟按键
  661. document.getElementById('foot-menu-wrap').style.display = 'flex';
  662. this.pageData.footMenuHeight = 40; // 设置底部菜单高度为40px
  663. this.getInitSize(); // 重新计算视频尺寸
  664. this.changeVideoStyle(); // 重新设置视频尺寸
  665. break
  666. case 'shearplate':
  667. // 粘贴板按钮
  668. this.shearplate();
  669. break;
  670. case 'shake':
  671. // 摇一摇
  672. if(this.sendWsCommand({ type: 'shakeit' })) {
  673. this.$toast('操作成功,如有异常请联系客服');
  674. } else {
  675. this.$toast('操作失败,请联系客服');
  676. }
  677. break;
  678. case 'blow':
  679. // 吹一吹
  680. if(this.sendWsCommand({ type: 'blow' })) {
  681. this.$toast('操作成功,如有异常请联系客服');
  682. } else {
  683. this.$toast('操作失败,请联系客服');
  684. }
  685. break;
  686. }
  687. },
  688. // 切换云机
  689. async changeCloudHandle(cloudData) {
  690. try {
  691. // 保存当前云机数据
  692. this.activeCloud = cloudData;
  693. // 重置相关数据
  694. this.closeChannel();
  695. // 重置重连次数
  696. this.doConnectDirectivesRequestNum = 1;
  697. // 重置 end
  698. if(this.sdkLoadStatus === 'success') {
  699. // 开始运行程序
  700. this.$nextTick(()=> this.start(cloudData) );
  701. }else {
  702. console.log('SDK加载失败');
  703. }
  704. } catch (error) {
  705. console.log('changeCloud error', error);
  706. }
  707. },
  708. // 重新设置视频尺寸
  709. changeVideoStyle() {
  710. this.$nextTick(() => {
  711. // 获取video元素
  712. const video = document.getElementById("videoRef").getElementsByTagName('video')[0];
  713. video.style.width = this.pageData.videoWidth + 'px';
  714. video.style.height = this.pageData.videoHeight + 'px';
  715. });
  716. },
  717. // 三键
  718. sendKey (keyCode) {
  719. try {
  720. this.engine?.sendKey(keyCode);
  721. // 重置超时无操作定时器
  722. this.$refs.timeoutNoOpsRef?.noOperationSetTimeout();
  723. } catch (error) {
  724. console.log('sendKey error', error);
  725. }
  726. },
  727. // popup粘贴板按钮点击事件
  728. shearplate(){
  729. // 调用InputCopy组件的pasteText方法读取粘贴板
  730. this.$refs.inputCopyRef.pasteText();
  731. },
  732. // 打开去取云机内的粘贴板内容
  733. openPasteboard(text){
  734. this.$refs.cloudPhoneClipboardRef.init(text);
  735. },
  736. // 退出功能
  737. exit() {
  738. // 关闭通道
  739. this.closeChannel();
  740. // 获取当前环境
  741. const env = isBrowserEnvironment();
  742. // ios环境下 直接使用浏览器api返回上一页
  743. if(env.isBrowser && !env.isMiniProgramWebview && env.isIPhone && env.isTopWindow) {
  744. // 上面的方法执行未生效就走这里
  745. if (window.history.length > 1) {
  746. return window.history.back();
  747. }
  748. }
  749. uni && uni.reLaunch({ url: '/pages/index/index' });
  750. },
  751. // 发送业务指令通道消息
  752. sendWsCommand(data) {
  753. if(this.doConnectDirectivesWs.readyState === 1) {
  754. this.doConnectDirectivesWs.send(JSON.stringify(data));
  755. return true;
  756. }
  757. return false;
  758. },
  759. // 初始化日志上报实例
  760. initLogReport() {
  761. // 初始化日志上报实例
  762. this.logReportObj = new logReport({ request: this.$axios });
  763. uni.getEnv((res) => {
  764. // 设置上报参数
  765. this.logReportObj.setParams({ clientType: Object.keys(res)[0] });
  766. })
  767. },
  768. // 关闭通道
  769. async closeChannel() {
  770. try {
  771. // 关闭日志上报
  772. this.logReportObj?.destroy();
  773. // 关闭webRTC
  774. this.engine?.disconnect && this.engine?.disconnect();
  775. // 关闭业务指令通道
  776. this.doConnectDirectivesWs?.close();
  777. } catch (error) {
  778. console.log('closeChannel error', error);
  779. }
  780. },
  781. // 开始运行程序
  782. async start(activeCloud) {
  783. console.log('start activeCloud', activeCloud);
  784. try {
  785. this.$toast.loading({
  786. className: 'rtc-loading',
  787. duration: 0, // 持续展示 toast
  788. message: `设备(${activeCloud.userCardId})正在获取...`,
  789. });
  790. // 初始化日志上报
  791. this.initLogReport();
  792. // 调用接口获取卡连接数据
  793. const cardData = await this.getConnectData(this.parametersData);
  794. // 判断卡的连接方式
  795. const connectData = await this.judgeConnectType(cardData);
  796. // 保存卡连接信息
  797. this.connectData = connectData;
  798. this.initWebRtc();
  799. } catch (error) {
  800. console.log('start error', error);
  801. }
  802. },
  803. }
  804. }
  805. </script>
  806. <style lang="scss" scoped>
  807. html{
  808. background-color: #000;
  809. }
  810. // 动态生成 从 0 到 100px 的样式
  811. @for $i from 0 through 100 {
  812. .mb-#{$i} {
  813. margin-bottom: #{$i}px;
  814. }
  815. .mt-#{$i} {
  816. margin-top: #{$i}px;
  817. }
  818. .ml-#{$i} {
  819. margin-left: #{$i}px;
  820. }
  821. .mr-#{$i} {
  822. margin-right: #{$i}px;
  823. }
  824. }
  825. $-radeus-12: 12px;
  826. $-bg-yellow: rgb(255, 253, 241);
  827. .rtc-page{
  828. position: relative;
  829. font-size: 14px;
  830. .video-wrapper{
  831. position: relative;
  832. }
  833. }
  834. .cover-bg{
  835. background-color: #000;
  836. }
  837. #foot-menu-wrap{
  838. border-width: 0px;
  839. position: absolute;
  840. left: 0px;
  841. bottom: 0px;
  842. width: 100%;
  843. // height: 40px; // 三大功能键高度,通过vue动态添加
  844. background: inherit;
  845. background-color: rgba(0, 12, 23, 1);
  846. border: none;
  847. border-radius: 0px;
  848. -moz-box-shadow: none;
  849. -webkit-box-shadow: none;
  850. box-shadow: none;
  851. z-index: 1;
  852. display: flex;
  853. justify-content: space-evenly;
  854. align-items: center;
  855. color: #fff;
  856. }
  857. //
  858. .rtc-page >>> .van-toast.rtc-loading{
  859. white-space: nowrap;
  860. }
  861. </style>