rtc.vue 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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.destroyListener();
  233. },
  234. methods: {
  235. // 初始化页面监听事件
  236. initListener() {
  237. // 禁止双击缩放
  238. document.addEventListener('dblclick', this.preventDefault);
  239. // 添加监听 页面显示或隐藏 事件
  240. document.addEventListener('visibilitychange', this.visibilitychanged);
  241. },
  242. // 销毁页面监听事件
  243. destroyListener() {
  244. // 允许双击缩放
  245. document.removeEventListener('dblclick', this.preventDefault);
  246. // 移除监听 页面显示或隐藏 事件
  247. document.removeEventListener('visibilitychange', this.visibilitychanged);
  248. },
  249. // 阻止默认事件
  250. preventDefault(e) {
  251. e.preventDefault();
  252. },
  253. // 监听 页面显示或隐藏 执行的函数
  254. visibilitychanged() {
  255. // 获取当前环境
  256. const env = isBrowserEnvironment();
  257. // 获取当前页面的可见性状态
  258. const visibilityState = document.visibilityState;
  259. if (visibilityState === 'visible') {
  260. // 页面显示时的逻辑
  261. // 网页重载
  262. if (env.isBrowser && env.isTopWindow && env.isIPhone) {
  263. location.reload();
  264. }
  265. } else if (visibilityState === 'hidden') {
  266. // 页面隐藏时的逻辑
  267. // video.pause();
  268. } else if (visibilityState === 'prerender') {
  269. // 页面预渲染时的逻辑
  270. console.log('页面处于预渲染状态');
  271. } else if (visibilityState === 'unloaded') {
  272. // 页面即将卸载时的逻辑 移除监听
  273. document.removeEventListener('visibilitychange', this.visibilitychanged);
  274. }
  275. },
  276. // 获取初始化尺寸
  277. getInitSize() {
  278. // 获取窗口尺寸
  279. this.pageData.height = window.innerHeight;
  280. this.pageData.width = window.innerWidth;
  281. // 计算视频尺寸 webRTC需要做成16:9的画面
  282. let videoWidth = this.pageData.width;
  283. let videoHeight = this.pageData.height - this.pageData.footMenuHeight;
  284. // 计算当前视口的宽高比
  285. const currentRatio = videoWidth / videoHeight;
  286. console.log(`当前视口的宽高比: ${currentRatio}`);
  287. // 9:16 的目标比例
  288. const targetRatio = 9 / 16;
  289. // 判断当前视口的宽高比与目标比例的关系
  290. if (currentRatio > targetRatio) {
  291. // 当前视口的宽高比大于目标比例,说明宽度“过宽”,需要以高度为基准
  292. console.log("当前视口宽度过宽,应以高度为基准调整宽度");
  293. this.pageData.videoWidth = videoHeight * targetRatio;
  294. this.pageData.videoHeight = videoHeight;
  295. console.log(`1目标: 宽${this.pageData.videoWidth},高${this.pageData.videoHeight}`);
  296. } else {
  297. // 当前视口的宽高比小于目标比例,说明高度“过高”,需要以宽度为基准
  298. console.log("当前视口高度过高,应以宽度为基准调整高度");
  299. this.pageData.videoWidth = videoWidth;
  300. this.pageData.videoHeight = videoWidth / targetRatio;
  301. console.log(`2目标: 宽${this.pageData.videoWidth},高${this.pageData.videoHeight}`);
  302. }
  303. },
  304. // 获取卡的信息
  305. async getConnectData({isWeixin, merchantSign}) {
  306. let userCardId = this.activeCloud.userCardId;
  307. try {
  308. // 设置上报参数
  309. this.logReportObj.setParams({userCardId});
  310. let isWx = this.$userAgent.isWx;
  311. let clientType = (+isWeixin || isWx) ? 'wx' : undefined;
  312. // 设置上报参数
  313. this.logReportObj.setParams({userCardId});
  314. clientType && this.logReportObj.setParams({clientType});
  315. const res = await this.$axios.$post('/resources/user/cloud/connect', { userCardId }, {
  316. headers: {
  317. merchantSign,
  318. },
  319. });
  320. if (!res.success) {
  321. // 设置日志 推流状态为失败,和链接状态
  322. this.logReportObj.setParams({plugFowStatus: 2, linkWay: this.logReportObj.RESPONSE_CODE[res.status] || 0, linkEndTime: this.logReportObj.formatDate(new Date())});
  323. // 日志上报
  324. this.logReportObj.collectLog(
  325. `接口获取数据失败:
  326. url: /api/resources/user/cloud/connect
  327. method: post
  328. 参数: ${JSON.stringify({ userCardId })}
  329. 响应: ${JSON.stringify(res)}`
  330. );
  331. // res.status状态码枚举值 0: 正常
  332. const statusEnum = {
  333. // 5200:RBD资源挂载中
  334. 5200: '网络异常,请稍后重试',
  335. // 入使用排队9.9,年卡
  336. 5220: '云手机正在一键修复中',
  337. 5203: '正在排队中,请稍等',
  338. // 9.9年卡连接异常,重新进入排队
  339. 5204: '云机异常,正在为你重新分配云机',
  340. 5228: '卡的网络状态为差',
  341. 5229: '接口返回链接信息缺失',
  342. };
  343. // NOTE 这里可设置重连机制, 重连次数上限6次, 每次重连间隔3秒, 暂不做重连
  344. // 提示错误信息
  345. this.$toast(statusEnum[res.status] || '网络异常,请稍后重试');
  346. return Promise.reject(new Error(statusEnum[res.status] || '网络异常,请稍后重试'));
  347. }
  348. return res.data;
  349. }catch (error) {
  350. // 设置上报参数
  351. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  352. // 日志上报
  353. this.logReportObj.collectLog(
  354. `接口获取数据失败:
  355. url: /api/resources/user/cloud/connect
  356. method: post
  357. 参数: ${JSON.stringify({ userCardId })}
  358. 响应: ${JSON.stringify(error)}`
  359. );
  360. console.log('error connectAxios:', error);
  361. return Promise.reject(error);
  362. }
  363. },
  364. // 判断卡的连接方式
  365. async judgeConnectType(cardData) {
  366. try {
  367. // 设置上报参数
  368. this.logReportObj.setParams({videoType: cardData.videoCode.toLowerCase(), resourceId: cardData.resourceId});
  369. // 不支持webRTC跳转到指定的页面进行拉流
  370. if (!cardData.isWebrtc) {
  371. // 关闭日志上报
  372. this.logReportObj?.destroy();
  373. // 跳转指定页面
  374. location.replace(`${location.origin}/h5/webRtcYJ/WXtrialInterface.html${location.search}`)
  375. return Promise.reject();
  376. }
  377. // 是否支持webRTC
  378. if (!this.isSupportRtc) {
  379. // 设置日志 推流状态为失败
  380. this.logReportObj.setParams({plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  381. // 日志上报
  382. this.logReportObj.collectLog(`${+this.parametersData.isWeixin ? '微信小程序' : ''}当前版本暂不支持使用`);
  383. this.$dialog.alert({
  384. title: '提示',
  385. message: '当前环境不支持使用,可下载谷歌浏览器或客户端进行使用',
  386. confirmButtonText: '确定',
  387. confirmButtonColor: '#3cc51f',
  388. callback: (_, done) => {
  389. done();
  390. this.exit();
  391. }
  392. })
  393. return Promise.reject(new Error('当前浏览器不支持webRTC'));
  394. }
  395. // webRtc连接,需获取连接中转地址
  396. if (cardData.webrtcNetworkAnalysis) {
  397. // 如果有网络分析的请求地址, 则请求,否则失败
  398. const { data: webrtcNetworkAnalysisReq }= await request.get(cardData.webrtcNetworkAnalysis); // 这个接口单独使用axios请求, 因为返回的数据跟封装的数据结构不一统一,是其他平台的接口,所以单独请求
  399. if (webrtcNetworkAnalysisReq !== null && webrtcNetworkAnalysisReq.success && webrtcNetworkAnalysisReq.data) {
  400. // 保存获取的连接地址到connect的请求的响应中, 方便后面使用
  401. cardData.webrtcNetwork = webrtcNetworkAnalysisReq.data;
  402. // 设置上报参数
  403. this.logReportObj.setParams({transferServerIp: webrtcNetworkAnalysisReq.data});
  404. return cardData;
  405. }else{
  406. // 设置上报参数
  407. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  408. // 日志上报
  409. this.logReportObj.collectLog(
  410. `webRtc连接,获取中转地址失败:
  411. url: ${cardData.webrtcNetworkAnalysis}
  412. method: get
  413. 参数: 无
  414. 响应: ${JSON.stringify(webrtcNetworkAnalysisReq)}`
  415. );
  416. // 弹窗并退出
  417. this.$dialog.alert({
  418. title: '提示',
  419. message: '访问失败,请稍后重试',
  420. confirmButtonText: '确定',
  421. confirmButtonColor: '#3cc51f',
  422. beforeClose: (action, done) => {
  423. done()
  424. this.exit();
  425. }
  426. })
  427. return Promise.reject(new Error('网络分析请求失败'));
  428. }
  429. }else{
  430. // 设置上报参数
  431. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2});
  432. // 日志上报
  433. this.logReportObj.collectLog(
  434. `webRtc连接,获取请求中转地址为空:
  435. url: /api/resources/user/cloud/connect
  436. method: post
  437. 参数: ${JSON.stringify({ userCardId: this.activeCloud.userCardId })}
  438. 响应: ${JSON.stringify(res)}`
  439. );
  440. return Promise.reject(new Error('网络分析请求地址不存在'));
  441. }
  442. } catch (error) {
  443. console.log('判断卡的连接方式', error);
  444. return Promise.reject(error);
  445. }
  446. },
  447. // 初始化webRTC及相关配置
  448. initWebRtc() {
  449. try {
  450. // 获取挂载的容器元素
  451. const videoRef = document.getElementById("videoRef");
  452. // 解构connectData中的数据
  453. const { sn: topic, cardToken: authToken, localIp, internetHttps, internetHttp, webrtcNetwork, webrtcTransferCmnet, webrtcTransferTelecom, webrtcTransferUnicom, videoCode } = this.connectData;
  454. // 判断长连接的协议方式
  455. const isWss = location.protocol === 'https:';
  456. // 生成连接地址
  457. const url = `${isWss ? 'wss://' : 'ws://'}${isWss ? internetHttps : internetHttp}/nats`;
  458. let quality = localStorage.getItem('definitionValue') ?? '自动';
  459. // 统一使用三网解析地址
  460. const ICEServerUrl = [
  461. { "CMNET": webrtcNetwork }, // 移动
  462. { 'CHINANET-GD': webrtcNetwork }, // 电信
  463. { 'UNICOM-GD': webrtcNetwork }, // 联通
  464. ];
  465. // 配置连接参数
  466. const connection = {
  467. mount: videoRef,
  468. displaySize: { // 视频在页面显示的尺寸 必填
  469. width: this.pageData.videoWidth,
  470. height: this.pageData.videoHeight,
  471. },
  472. topic, // SN号 必填
  473. url, //信令服务地址 必填
  474. ICEServerUrl,
  475. forwardServerAddress: '', // 转发服务器地址
  476. ip: localIp, // 实例ip
  477. controlToken: '', // 控制token
  478. width: 720, // 推流视频宽度 必填
  479. height: 1080, // 推流视频高度 必填
  480. cardWidth: 0, // 云机系统分辨率 宽 必填
  481. cardHeight: 0, // 云机系统分辨率 高 必填
  482. cardDensity: 0, // 云机系统显示 密度 必填
  483. authToken, //拉流鉴权 token 必填
  484. quality, // 画质(码率) 超清 | 高清 | 标清 | 流畅
  485. fps: 30, //必填
  486. videoCodec: videoCode, // 视频编码格式 必填
  487. videoCodecMethod: true, // 硬编true | 软编false
  488. isMuted: false, // 是否静音
  489. isAllowedOpenCamera: true, // 是否允许打开摄像头
  490. sendFollow: true, // 是否允许主控转发文本到实例
  491. callback: (event)=> {console.log('webRTC回调', event);}
  492. };
  493. // 设置日志参数 推流质量
  494. this.logReportObj.setParams({imageQuality: quality});
  495. // 获取SDK类
  496. const MediaSdk = window.rtc_sdk.MediaSdk;
  497. // 初始化 SDK
  498. this.engine = new MediaSdk();
  499. console.log('RtcEngineConfig==', connection)
  500. // 初始化 SDK 并传入连接参数
  501. this.engine.RtcEngine(connection);
  502. // 监听回调方法
  503. this.eventCallbackFunction();
  504. } catch (error) {
  505. console.log('webRTC初始化失败', error);
  506. }
  507. },
  508. // webRTC状态回调监听回调方法
  509. eventCallbackFunction() {
  510. const engine = this.engine;
  511. // 连接成功
  512. engine.on('CONNECT_SUCCESS', (r) => {
  513. console.log("webrtc连接成功====★★★★★", r);
  514. if (r.code === 1005) { // 1005: 拉流鉴权成功
  515. // 清除loading
  516. this.$toast.clear();
  517. // 设置日志 推流状态为成功
  518. let now = new Date();
  519. this.logReportObj.setParams({plugFowStatus: 1, linkWay: 1, timeConsuming: now.getTime() - this.logReportObj.timeStartTime, linkEndTime: this.logReportObj.formatDate(now)});
  520. // 日志上报
  521. this.logReportObj.collectLog(`拉流成功`);
  522. // 初始化业务指令通道
  523. this.initControlChannel();
  524. // 查询超过指定触碰时间是否提示关闭弹窗
  525. this.$refs.timeoutNoOpsRef.pushflowPopup();
  526. // 获取云机剩余时长
  527. this.$refs.timeBalanceRef.getResidueTime();
  528. }
  529. });
  530. // 连接关闭
  531. engine.on('CONNECT_CLOSE', (r) => {
  532. console.log("webrtc关闭====★★★★★", r);
  533. });
  534. // 网络连接统计信息监听
  535. engine.on('NETWORK_STATS', (r) => {
  536. console.log("webrtc网络连接统计信息监听====★★★★★", r);
  537. this.rtcNetwork = r;
  538. });
  539. // 连接异常
  540. engine.on('CONNECT_ERROR', (r) => {
  541. console.log("webrtc异常状态====★★★★★", r);
  542. // 异常状态枚举值
  543. const statusEnum = {
  544. 10011: '连接超时',
  545. 10012: '连接失败',
  546. 1002: 'rtc连接失败',
  547. 1003: 'rtc异常断开',
  548. 1004: 'rtc连接失败',
  549. 1006: '鉴权失败',
  550. };
  551. // 设置日志 推流状态为失败
  552. this.logReportObj.setParams({plugFowStatus: 2, linkWay: 0, linkEndTime: this.logReportObj.formatDate(new Date())});
  553. // 日志上报
  554. this.logReportObj.collectLog( `${statusEnum[r.code] || '连接异常'}: 消息: ${JSON.stringify(r)}` );
  555. this.$dialog.alert({
  556. title: '提示',
  557. message: '链接超时',
  558. confirmButtonText: '确定',
  559. confirmButtonColor: '#3cc51f',
  560. beforeClose: (action, done) => {
  561. done()
  562. this.exit()
  563. }
  564. })
  565. });
  566. // 显示区域大小发生改变 响应
  567. engine.on('RECEIVE_RESOLUTION', (r) => {
  568. // 分辨率大小发生改变,响应
  569. console.log("分辨率大小发生改变,响应 => RECEIVE_RESOLUTION", r);
  570. });
  571. },
  572. // 业务指令通道初始化
  573. initControlChannel() {
  574. try {
  575. // 初始化业务指令通道
  576. let { internetHttps, internetHttp, localIp, cardToken } = this.connectData;
  577. const isWss = location.protocol === 'https:';
  578. let cUrl = `${isWss ? 'wss' : 'ws'}://${isWss ? internetHttps : internetHttp}/businessChannel?cardIp=${localIp}&token=${cardToken}&type=directives`;
  579. this.doConnectDirectivesWs = new WebSocket(cUrl);
  580. this.doConnectDirectivesWs.binaryType = 'arraybuffer';
  581. // 清除定时器
  582. if (this.doConnectDirectivesIntervalerPing) {
  583. clearInterval(this.doConnectDirectivesIntervalerPing);
  584. }
  585. // 链接成功
  586. this.doConnectDirectivesWs.onopen = (e) => {
  587. // 日志上报
  588. this.logReportObj.collectLog( `消息: 业务通道连接成功` );
  589. // 重置重连次数
  590. this.doConnectDirectivesRequestNum = 1;
  591. // 设置定时器 每3秒发送一次心跳
  592. this.doConnectDirectivesIntervalerPing = setInterval(() => {
  593. if (this.doConnectDirectivesWs.readyState === 1) {
  594. this.sendWsCommand({ type: 'ping' });
  595. } else {
  596. clearInterval(this.doConnectDirectivesIntervalerPing);
  597. }
  598. }, 3000);
  599. // 输入法: 本地输入法 1 云机输入法 2
  600. this.sendWsCommand({ type: 'InputMethod', data: { type: 2 } });
  601. }
  602. // 接受到的消息
  603. this.doConnectDirectivesWs.onmessage = res => {
  604. const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
  605. switch (result.type) {
  606. case 'reProduceText':
  607. this.$native.clipboard.writeText(result.data.text);
  608. break
  609. case 'downAdnInstallRep':
  610. this.$toast(result.data.msg)
  611. break
  612. // 接受到这个消息就自动退出云机
  613. case 'exitPhone':
  614. this.exit();
  615. break
  616. }
  617. }
  618. // 链接报错的回调
  619. this.doConnectDirectivesWs.onerror = res => {
  620. // 设置日志
  621. this.logReportObj.setParams({plugFowStatus: 1, linkWay: 0, linkEndTime: this.logReportObj.formatDate(new Date())});
  622. // 日志上报
  623. this.logReportObj.collectLog(
  624. `业务指令通道报错:
  625. url: ${res.target.url}
  626. type: ${res.type}
  627. 消息: ${JSON.stringify(res)}`
  628. );
  629. if (this.doConnectDirectivesRequestNum > this.doConnectDirectivesRequestNumMax) {
  630. return this.exit();
  631. }else{
  632. // 重连次数加1
  633. ++this.doConnectDirectivesRequestNum;
  634. // 重连
  635. this.initControlChannel();
  636. }
  637. }
  638. } catch (error) {
  639. console.log('initControlChannel error', error);
  640. }
  641. },
  642. /**
  643. * popup 功能按钮点击事件
  644. * @param {Object} val 传递的参数
  645. * @description 传递的参数格式: { code: 'hideKey', label: '隐藏虚拟键', icon: 'icon-hide' }
  646. */
  647. funcHandle({code}) {
  648. console.log('funcHandle code:', code);
  649. switch (code) {
  650. case 'hideKey':
  651. // 隐藏虚拟按键
  652. document.getElementById('foot-menu-wrap').style.display = 'none';
  653. this.pageData.footMenuHeight = 0; // 设置底部菜单高度为0
  654. this.getInitSize(); // 重新计算视频尺寸
  655. this.changeVideoStyle(); // 重新设置视频尺寸
  656. break;
  657. case 'showKey':
  658. // 显示虚拟按键
  659. document.getElementById('foot-menu-wrap').style.display = 'flex';
  660. this.pageData.footMenuHeight = 40; // 设置底部菜单高度为40px
  661. this.getInitSize(); // 重新计算视频尺寸
  662. this.changeVideoStyle(); // 重新设置视频尺寸
  663. break
  664. case 'shearplate':
  665. // 粘贴板按钮
  666. this.shearplate();
  667. break;
  668. case 'shake':
  669. // 摇一摇
  670. if(this.sendWsCommand({ type: 'shakeit' })) {
  671. this.$toast('操作成功,如有异常请联系客服');
  672. } else {
  673. this.$toast('操作失败,请联系客服');
  674. }
  675. break;
  676. case 'blow':
  677. // 吹一吹
  678. if(this.sendWsCommand({ type: 'blow' })) {
  679. this.$toast('操作成功,如有异常请联系客服');
  680. } else {
  681. this.$toast('操作失败,请联系客服');
  682. }
  683. break;
  684. }
  685. },
  686. // 切换云机
  687. async changeCloudHandle(cloudData) {
  688. try {
  689. // 保存当前云机数据
  690. this.activeCloud = cloudData;
  691. // 重置相关数据
  692. // 关闭日志上报
  693. this.logReportObj?.destroy();
  694. // 关闭webRTC
  695. this.engine?.disconnect && this.engine?.disconnect();
  696. // 关闭业务指令通道
  697. this.doConnectDirectivesWs?.close();
  698. // 重置重连次数
  699. this.doConnectDirectivesRequestNum = 1;
  700. // 重置 end
  701. if(this.sdkLoadStatus === 'success') {
  702. // 开始运行程序
  703. this.start(cloudData);
  704. }else {
  705. console.log('SDK加载失败');
  706. }
  707. } catch (error) {
  708. console.log('changeCloud error', error);
  709. }
  710. },
  711. // 重新设置视频尺寸
  712. changeVideoStyle() {
  713. this.$nextTick(() => {
  714. // 获取video元素
  715. const video = document.getElementById("videoRef").getElementsByTagName('video')[0];
  716. video.style.width = this.pageData.videoWidth + 'px';
  717. video.style.height = this.pageData.videoHeight + 'px';
  718. });
  719. },
  720. // 三键
  721. sendKey (keyCode) {
  722. try {
  723. this.engine?.sendKey(keyCode);
  724. // 重置超时无操作定时器
  725. this.$refs.timeoutNoOpsRef?.noOperationSetTimeout();
  726. } catch (error) {
  727. console.log('sendKey error', error);
  728. }
  729. },
  730. // popup粘贴板按钮点击事件
  731. shearplate(){
  732. // 调用InputCopy组件的pasteText方法读取粘贴板
  733. this.$refs.inputCopyRef.pasteText();
  734. },
  735. // 打开去取云机内的粘贴板内容
  736. openPasteboard(text){
  737. this.$refs.cloudPhoneClipboardRef.init(text);
  738. },
  739. // 退出功能
  740. exit() {
  741. // 关闭日志上报
  742. this.logReportObj?.destroy();
  743. // 关闭webRTC
  744. this.engine?.disconnect && this.engine?.disconnect();
  745. // 关闭业务指令通道
  746. this.doConnectDirectivesWs?.close();
  747. // 获取当前环境
  748. const env = isBrowserEnvironment();
  749. // ios环境下 直接使用浏览器api返回上一页
  750. if(env.isBrowser && !env.isMiniProgramWebview && env.isIPhone && env.isTopWindow) {
  751. // 上面的方法执行未生效就走这里
  752. if (window.history.length > 1) {
  753. return window.history.back();
  754. }
  755. }
  756. uni && uni.reLaunch({ url: '/pages/index/index' });
  757. },
  758. // 发送业务指令通道消息
  759. sendWsCommand(data) {
  760. if(this.doConnectDirectivesWs.readyState === 1) {
  761. this.doConnectDirectivesWs.send(JSON.stringify(data));
  762. return true;
  763. }
  764. return false;
  765. },
  766. // 初始化日志上报实例
  767. initLogReport() {
  768. // 初始化日志上报实例
  769. this.logReportObj = new logReport({ request: this.$axios });
  770. uni.getEnv((res) => {
  771. // 设置上报参数
  772. this.logReportObj.setParams({ clientType: Object.keys(res)[0] });
  773. })
  774. },
  775. // 开始运行程序
  776. async start(activeCloud) {
  777. console.log('start activeCloud', activeCloud);
  778. try {
  779. this.$toast.loading({
  780. className: 'rtc-loading',
  781. duration: 0, // 持续展示 toast
  782. message: `设备(${activeCloud.userCardId})正在获取...`,
  783. });
  784. // 初始化日志上报
  785. this.initLogReport();
  786. // 调用接口获取卡连接数据
  787. const cardData = await this.getConnectData(this.parametersData);
  788. // 判断卡的连接方式
  789. const connectData = await this.judgeConnectType(cardData);
  790. // 保存卡连接信息
  791. this.connectData = connectData;
  792. this.initWebRtc();
  793. } catch (error) {
  794. console.log('start error', error);
  795. }
  796. },
  797. }
  798. }
  799. </script>
  800. <style lang="scss" scoped>
  801. html{
  802. background-color: #000;
  803. }
  804. // 动态生成 从 0 到 100px 的样式
  805. @for $i from 0 through 100 {
  806. .mb-#{$i} {
  807. margin-bottom: #{$i}px;
  808. }
  809. .mt-#{$i} {
  810. margin-top: #{$i}px;
  811. }
  812. .ml-#{$i} {
  813. margin-left: #{$i}px;
  814. }
  815. .mr-#{$i} {
  816. margin-right: #{$i}px;
  817. }
  818. }
  819. $-radeus-12: 12px;
  820. $-bg-yellow: rgb(255, 253, 241);
  821. .rtc-page{
  822. position: relative;
  823. font-size: 14px;
  824. .video-wrapper{
  825. position: relative;
  826. }
  827. }
  828. .cover-bg{
  829. background-color: #000;
  830. }
  831. #foot-menu-wrap{
  832. border-width: 0px;
  833. position: absolute;
  834. left: 0px;
  835. bottom: 0px;
  836. width: 100%;
  837. // height: 40px; // 三大功能键高度,通过vue动态添加
  838. background: inherit;
  839. background-color: rgba(0, 12, 23, 1);
  840. border: none;
  841. border-radius: 0px;
  842. -moz-box-shadow: none;
  843. -webkit-box-shadow: none;
  844. box-shadow: none;
  845. z-index: 1;
  846. display: flex;
  847. justify-content: space-evenly;
  848. align-items: center;
  849. color: #fff;
  850. }
  851. //
  852. .rtc-page >>> .van-toast.rtc-loading{
  853. white-space: nowrap;
  854. }
  855. </style>