rtc.vue 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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. rtcNetwork: {
  165. currentRoundTripTime: 0, // 当前往返时间(网络延迟)
  166. }, // webRtc网络分析数据
  167. doConnectDirectivesWs: null, // 云手机指令通道
  168. doConnectDirectivesIntervalerPing: null, // 业务通道定时标识 云手机指令通道心跳
  169. doConnectDirectivesRequestNum: 1, // 业务通道重连次数
  170. doConnectDirectivesRequestNumMax: 6, // 业务通道重连次数上限
  171. // 右侧popup显隐
  172. levitatedSphereVisible: false,
  173. }
  174. },
  175. // 页面初始化后触发
  176. async fetch() {
  177. // 获取页面传递参数
  178. this.parametersData = this.$route.query;
  179. // 获取用户所有云机列表
  180. await this.getCloudList();
  181. // 获取当前云机信息
  182. this.activeCloud = this.cloudList.find(item => item.userCardId === +this.parametersData.userCardId);
  183. // 获取所有云机套餐信息
  184. this.getMealIconInfo();
  185. // 获取云机分组
  186. this.getCloudGroupId();
  187. },
  188. computed: {
  189. // 是否为微信浏览器环境
  190. isWeChatBrowser() {
  191. return this.$userAgent.isWx;
  192. },
  193. },
  194. created() {
  195. this.$toast.loading({
  196. duration: 0, // 持续展示 toast
  197. message: `设备(${this.activeCloud.userCardId})正在获取...`,
  198. });
  199. // 设置html标签的背景为黑色
  200. document.body.style.background = '#000';
  201. // 定义全局变量 用于监听sdk加载状态
  202. window.$_script_loadHandler = async ()=> {
  203. console.log('$_script_loadHandler: SDK加载成功');
  204. this.sdkLoadStatus = 'success';
  205. // 初始化日志上报
  206. this.initLogReport();
  207. // 调用接口获取卡连接数据
  208. const cardData = await this.getConnectData(this.parametersData);
  209. // 判断卡的连接方式
  210. const connectData = await this.judgeConnectType(cardData);
  211. // 保存卡连接信息
  212. this.connectData = connectData;
  213. this.initWebRtc();
  214. };
  215. window.$_script_errHandler = ()=> {
  216. console.log('SDK加载失败');
  217. this.sdkLoadStatus = 'error';
  218. }
  219. },
  220. mounted() {
  221. // 获取窗口尺寸
  222. this.getInitSize();
  223. window.onresize = () => {
  224. console.log('窗口尺寸变化');
  225. this.getInitSize()
  226. };
  227. // 初始化页面监听事件
  228. this.initListener();
  229. },
  230. // 页面销毁前触发
  231. beforeDestroy() {
  232. // 销毁页面监听事件
  233. this.destroyListener();
  234. },
  235. methods: {
  236. // 初始化页面监听事件
  237. initListener() {
  238. // 禁止双击缩放
  239. document.addEventListener('dblclick', this.preventDefault);
  240. // 添加监听 页面显示或隐藏 事件
  241. document.addEventListener('visibilitychange', this.visibilitychanged);
  242. },
  243. // 销毁页面监听事件
  244. destroyListener() {
  245. // 允许双击缩放
  246. document.removeEventListener('dblclick', this.preventDefault);
  247. // 移除监听 页面显示或隐藏 事件
  248. document.removeEventListener('visibilitychange', this.visibilitychanged);
  249. },
  250. // 阻止默认事件
  251. preventDefault(e) {
  252. e.preventDefault();
  253. },
  254. // 监听 页面显示或隐藏 执行的函数
  255. visibilitychanged() {
  256. // 获取当前环境
  257. const env = isBrowserEnvironment();
  258. // 获取当前页面的可见性状态
  259. const visibilityState = document.visibilityState;
  260. if (visibilityState === 'visible') {
  261. // 页面显示时的逻辑
  262. // 网页重载
  263. if (env.isBrowser && env.isTopWindow && env.isIPhone) {
  264. location.reload();
  265. }
  266. } else if (visibilityState === 'hidden') {
  267. // 页面隐藏时的逻辑
  268. // video.pause();
  269. } else if (visibilityState === 'prerender') {
  270. // 页面预渲染时的逻辑
  271. console.log('页面处于预渲染状态');
  272. } else if (visibilityState === 'unloaded') {
  273. // 页面即将卸载时的逻辑 移除监听
  274. document.removeEventListener('visibilitychange', this.visibilitychanged);
  275. }
  276. },
  277. // 获取初始化尺寸
  278. getInitSize() {
  279. // 获取窗口尺寸
  280. this.pageData.height = window.innerHeight;
  281. this.pageData.width = window.innerWidth;
  282. // 计算视频尺寸 webRTC需要做成16:9的画面
  283. let videoWidth = this.pageData.width;
  284. let videoHeight = this.pageData.height - this.pageData.footMenuHeight;
  285. // 计算当前视口的宽高比
  286. const currentRatio = videoWidth / videoHeight;
  287. console.log(`当前视口的宽高比: ${currentRatio}`);
  288. // 9:16 的目标比例
  289. const targetRatio = 9 / 16;
  290. // 判断当前视口的宽高比与目标比例的关系
  291. if (currentRatio > targetRatio) {
  292. // 当前视口的宽高比大于目标比例,说明宽度“过宽”,需要以高度为基准
  293. console.log("当前视口宽度过宽,应以高度为基准调整宽度");
  294. this.pageData.videoWidth = videoHeight * targetRatio;
  295. this.pageData.videoHeight = videoHeight;
  296. console.log(`1目标: 宽${this.pageData.videoWidth},高${this.pageData.videoHeight}`);
  297. } else {
  298. // 当前视口的宽高比小于目标比例,说明高度“过高”,需要以宽度为基准
  299. console.log("当前视口高度过高,应以宽度为基准调整高度");
  300. this.pageData.videoWidth = videoWidth;
  301. this.pageData.videoHeight = videoWidth / targetRatio;
  302. console.log(`2目标: 宽${this.pageData.videoWidth},高${this.pageData.videoHeight}`);
  303. }
  304. },
  305. // 获取卡的信息
  306. async getConnectData({isWeixin, merchantSign}) {
  307. let userCardId = this.activeCloud.userCardId;
  308. try {
  309. // 设置上报参数
  310. this.logReportObj.setParams({userCardId});
  311. let isWx = this.$userAgent.isWx;
  312. let clientType = (+isWeixin || isWx) ? 'wx' : undefined;
  313. // 设置上报参数
  314. this.logReportObj.setParams({userCardId});
  315. clientType && this.logReportObj.setParams({clientType});
  316. const res = await this.$axios.$post('/resources/user/cloud/connect', { userCardId }, {
  317. headers: {
  318. merchantSign,
  319. },
  320. });
  321. if (!res.success) {
  322. // 设置日志 推流状态为失败,和链接状态
  323. this.logReportObj.setParams({plugFowStatus: 2, linkWay: this.logReportObj.RESPONSE_CODE[res.status] || 0, linkEndTime: this.logReportObj.formatDate(new Date())});
  324. // 日志上报
  325. this.logReportObj.collectLog(
  326. `接口获取数据失败:
  327. url: /api/resources/user/cloud/connect
  328. method: post
  329. 参数: ${JSON.stringify({ userCardId })}
  330. 响应: ${JSON.stringify(res)}`
  331. );
  332. // res.status状态码枚举值 0: 正常
  333. const statusEnum = {
  334. // 5200:RBD资源挂载中
  335. 5200: '网络异常,请稍后重试',
  336. // 入使用排队9.9,年卡
  337. 5220: '云手机正在一键修复中',
  338. 5203: '正在排队中,请稍等',
  339. // 9.9年卡连接异常,重新进入排队
  340. 5204: '云机异常,正在为你重新分配云机',
  341. 5228: '卡的网络状态为差',
  342. 5229: '接口返回链接信息缺失',
  343. };
  344. // NOTE 这里可设置重连机制, 重连次数上限6次, 每次重连间隔3秒, 暂不做重连
  345. // 提示错误信息
  346. this.$toast(statusEnum[res.status] || '网络异常,请稍后重试');
  347. return Promise.reject(new Error(statusEnum[res.status] || '网络异常,请稍后重试'));
  348. }
  349. return res.data;
  350. }catch (error) {
  351. // 设置上报参数
  352. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  353. // 日志上报
  354. this.logReportObj.collectLog(
  355. `接口获取数据失败:
  356. url: /api/resources/user/cloud/connect
  357. method: post
  358. 参数: ${JSON.stringify({ userCardId })}
  359. 响应: ${JSON.stringify(error)}`
  360. );
  361. console.log('error connectAxios:', error);
  362. return Promise.reject(error);
  363. }
  364. },
  365. // 判断卡的连接方式
  366. async judgeConnectType(cardData) {
  367. try {
  368. // 设置上报参数
  369. this.logReportObj.setParams({videoType: cardData.videoCode.toLowerCase(), resourceId: cardData.resourceId});
  370. // 不支持webRTC跳转到指定的页面进行拉流
  371. if (!cardData.isWebrtc) {
  372. // 关闭日志上报
  373. this.logReportObj.destroy();
  374. // 跳转指定页面
  375. location.replace(`${location.origin}/h5/webRtcYJ/WXtrialInterface.html${location.search}`)
  376. return Promise.reject();
  377. }
  378. // 是否支持webRTC
  379. if (!this.isSupportRtc) {
  380. // 设置日志 推流状态为失败
  381. this.logReportObj.setParams({plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  382. // 日志上报
  383. this.logReportObj.collectLog(`${+this.parametersData.isWeixin ? '微信小程序' : ''}当前版本暂不支持使用`);
  384. this.$dialog.alert({
  385. title: '提示',
  386. message: '当前环境不支持使用,可下载谷歌浏览器或客户端进行使用',
  387. confirmButtonText: '确定',
  388. confirmButtonColor: '#3cc51f',
  389. callback: (_, done) => {
  390. done();
  391. this.exit();
  392. }
  393. })
  394. return Promise.reject(new Error('当前浏览器不支持webRTC'));
  395. }
  396. // webRtc连接,需获取连接中转地址
  397. if (cardData.webrtcNetworkAnalysis) {
  398. // 如果有网络分析的请求地址, 则请求,否则失败
  399. const { data: webrtcNetworkAnalysisReq }= await request.get(cardData.webrtcNetworkAnalysis); // 这个接口单独使用axios请求, 因为返回的数据跟封装的数据结构不一统一,是其他平台的接口,所以单独请求
  400. if (webrtcNetworkAnalysisReq !== null && webrtcNetworkAnalysisReq.success && webrtcNetworkAnalysisReq.data) {
  401. // 保存获取的连接地址到connect的请求的响应中, 方便后面使用
  402. cardData.webrtcNetwork = webrtcNetworkAnalysisReq.data;
  403. // 设置上报参数
  404. this.logReportObj.setParams({transferServerIp: webrtcNetworkAnalysisReq.data});
  405. return cardData;
  406. }else{
  407. // 设置上报参数
  408. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  409. // 日志上报
  410. this.logReportObj.collectLog(
  411. `webRtc连接,获取中转地址失败:
  412. url: ${cardData.webrtcNetworkAnalysis}
  413. method: get
  414. 参数: 无
  415. 响应: ${JSON.stringify(webrtcNetworkAnalysisReq)}`
  416. );
  417. // 弹窗并退出
  418. this.$dialog.alert({
  419. title: '提示',
  420. message: '访问失败,请稍后重试',
  421. confirmButtonText: '确定',
  422. confirmButtonColor: '#3cc51f',
  423. beforeClose: (action, done) => {
  424. done()
  425. this.exit();
  426. }
  427. })
  428. return Promise.reject(new Error('网络分析请求失败'));
  429. }
  430. }else{
  431. // 设置上报参数
  432. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2});
  433. // 日志上报
  434. this.logReportObj.collectLog(
  435. `webRtc连接,获取请求中转地址为空:
  436. url: /api/resources/user/cloud/connect
  437. method: post
  438. 参数: ${JSON.stringify({ userCardId: this.activeCloud.userCardId })}
  439. 响应: ${JSON.stringify(res)}`
  440. );
  441. return Promise.reject(new Error('网络分析请求地址不存在'));
  442. }
  443. } catch (error) {
  444. console.log('判断卡的连接方式', error);
  445. return Promise.reject(error);
  446. }
  447. },
  448. // 初始化webRTC及相关配置
  449. initWebRtc() {
  450. try {
  451. // 获取挂载的容器元素
  452. const videoRef = document.getElementById("videoRef");
  453. // 解构connectData中的数据
  454. const { sn: topic, cardToken: authToken, localIp, internetHttps, internetHttp, webrtcNetwork, webrtcTransferCmnet, webrtcTransferTelecom, webrtcTransferUnicom, videoCode } = this.connectData;
  455. // 判断长连接的协议方式
  456. const isWss = location.protocol === 'https:';
  457. // 生成连接地址
  458. const url = `${isWss ? 'wss://' : 'ws://'}${isWss ? internetHttps : internetHttp}/nats`;
  459. let quality = localStorage.getItem('definitionValue') ?? '自动';
  460. // 统一使用三网解析地址
  461. const ICEServerUrl = [
  462. { "CMNET": webrtcNetwork }, // 移动
  463. { 'CHINANET-GD': webrtcNetwork }, // 电信
  464. { 'UNICOM-GD': webrtcNetwork }, // 联通
  465. ];
  466. // 配置连接参数
  467. const connection = {
  468. mount: videoRef,
  469. displaySize: { // 视频在页面显示的尺寸 必填
  470. width: this.pageData.videoWidth,
  471. height: this.pageData.videoHeight,
  472. },
  473. topic, // SN号 必填
  474. url, //信令服务地址 必填
  475. ICEServerUrl,
  476. forwardServerAddress: '', // 转发服务器地址
  477. ip: localIp, // 实例ip
  478. controlToken: '', // 控制token
  479. width: 720, // 推流视频宽度 必填
  480. height: 1080, // 推流视频高度 必填
  481. cardWidth: 0, // 云机系统分辨率 宽 必填
  482. cardHeight: 0, // 云机系统分辨率 高 必填
  483. cardDensity: 0, // 云机系统显示 密度 必填
  484. authToken, //拉流鉴权 token 必填
  485. quality, // 画质(码率) 超清 | 高清 | 标清 | 流畅
  486. fps: 30, //必填
  487. videoCodec: videoCode, // 视频编码格式 必填
  488. videoCodecMethod: true, // 硬编true | 软编false
  489. isMuted: false, // 是否静音
  490. isAllowedOpenCamera: true, // 是否允许打开摄像头
  491. sendFollow: true, // 是否允许主控转发文本到实例
  492. callback: (event)=> {}
  493. };
  494. // 设置日志参数 推流质量
  495. this.logReportObj.setParams({imageQuality: quality});
  496. // 获取SDK类
  497. const MediaSdk = window.rtc_sdk.MediaSdk;
  498. // 初始化 SDK
  499. this.engine = new MediaSdk();
  500. console.log('RtcEngineConfig==', connection)
  501. // 初始化 SDK 并传入连接参数
  502. this.engine.RtcEngine(connection);
  503. // 监听回调方法
  504. this.eventCallbackFunction();
  505. } catch (error) {
  506. console.log('webRTC初始化失败', error);
  507. }
  508. },
  509. // webRTC状态回调监听回调方法
  510. eventCallbackFunction() {
  511. const engine = this.engine;
  512. // 连接成功
  513. engine.on('CONNECT_SUCCESS', (r) => {
  514. console.log("webrtc连接成功====★★★★★", r);
  515. if (r.code === 1005) { // 1005: 拉流鉴权成功
  516. // 设置日志 推流状态为成功
  517. let now = new Date();
  518. this.logReportObj.setParams({plugFowStatus: 1, linkWay: 1, timeConsuming: now.getTime() - this.logReportObj.timeStartTime, linkEndTime: this.logReportObj.formatDate(now)});
  519. // 日志上报
  520. this.logReportObj.collectLog(`拉流成功`);
  521. // 初始化业务指令通道
  522. this.initControlChannel();
  523. // 查询超过指定触碰时间是否提示关闭弹窗
  524. this.$refs.timeoutNoOpsRef.pushflowPopup();
  525. // 获取云机剩余时长
  526. this.$refs.timeBalanceRef.getResidueTime();
  527. }
  528. });
  529. // 连接关闭
  530. engine.on('CONNECT_CLOSE', (r) => {
  531. console.log("webrtc关闭====★★★★★", r);
  532. });
  533. // 网络连接统计信息监听
  534. engine.on('NETWORK_STATS', (r) => {
  535. this.rtcNetwork = r;
  536. });
  537. // 连接异常
  538. engine.on('CONNECT_ERROR', (r) => {
  539. console.log("webrtc异常状态====★★★★★", r);
  540. // 异常状态枚举值
  541. const statusEnum = {
  542. 10011: '连接超时',
  543. 10012: '连接失败',
  544. 1002: 'rtc连接失败',
  545. 1003: 'rtc异常断开',
  546. 1004: 'rtc连接失败',
  547. 1006: '鉴权失败',
  548. };
  549. // 设置日志 推流状态为失败
  550. this.logReportObj.setParams({plugFowStatus: 2, linkWay: 0, linkEndTime: this.logReportObj.formatDate(new Date())});
  551. // 日志上报
  552. this.logReportObj.collectLog( `${statusEnum[r.code] || '连接异常'}: 消息: ${JSON.stringify(r)}` );
  553. this.$dialog.alert({
  554. title: '提示',
  555. message: '链接超时',
  556. confirmButtonText: '确定',
  557. confirmButtonColor: '#3cc51f',
  558. beforeClose: (action, done) => {
  559. done()
  560. this.exit()
  561. }
  562. })
  563. });
  564. // 显示区域大小发生改变 响应
  565. engine.on('RECEIVE_RESOLUTION', (r) => {
  566. // 分辨率大小发生改变,响应
  567. console.log("分辨率大小发生改变,响应 => RECEIVE_RESOLUTION", r);
  568. });
  569. },
  570. // 业务指令通道初始化
  571. initControlChannel() {
  572. try {
  573. // 初始化业务指令通道
  574. let { internetHttps, internetHttp, localIp, cardToken } = this.connectData;
  575. const isWss = location.protocol === 'https:';
  576. let cUrl = `${isWss ? 'wss' : 'ws'}://${isWss ? internetHttps : internetHttp}/businessChannel?cardIp=${localIp}&token=${cardToken}&type=directives`;
  577. this.doConnectDirectivesWs = new WebSocket(cUrl);
  578. this.doConnectDirectivesWs.binaryType = 'arraybuffer';
  579. // 清除定时器
  580. if (this.doConnectDirectivesIntervalerPing) {
  581. clearInterval(this.doConnectDirectivesIntervalerPing);
  582. }
  583. // 链接成功
  584. this.doConnectDirectivesWs.onopen = (e) => {
  585. // 日志上报
  586. this.logReportObj.collectLog( `消息: 业务通道连接成功` );
  587. // 清除loading
  588. this.$toast.clear();
  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. } catch (error) {
  692. console.log('changeCloud error', error);
  693. }
  694. },
  695. // 重新设置视频尺寸
  696. changeVideoStyle() {
  697. this.$nextTick(() => {
  698. // 获取video元素
  699. const video = document.getElementById("videoRef").getElementsByTagName('video')[0];
  700. video.style.width = this.pageData.videoWidth + 'px';
  701. video.style.height = this.pageData.videoHeight + 'px';
  702. });
  703. },
  704. // 三键
  705. sendKey (keyCode) {
  706. try {
  707. this.engine?.sendKey(keyCode);
  708. // 重置超时无操作定时器
  709. this.$refs.timeoutNoOpsRef?.noOperationSetTimeout();
  710. } catch (error) {
  711. console.log('sendKey error', error);
  712. }
  713. },
  714. // popup粘贴板按钮点击事件
  715. shearplate(){
  716. // 调用InputCopy组件的pasteText方法读取粘贴板
  717. this.$refs.inputCopyRef.pasteText();
  718. },
  719. // 打开去取云机内的粘贴板内容
  720. openPasteboard(text){
  721. this.$refs.cloudPhoneClipboardRef.init(text);
  722. },
  723. // 退出功能
  724. exit() {
  725. // 关闭日志上报
  726. this.logReportObj.destroy();
  727. // 关闭webRTC
  728. this.engine.disconnect && this.engine.disconnect();
  729. // 关闭业务指令通道
  730. this.doConnectDirectivesWs && this.doConnectDirectivesWs.close();
  731. // 获取当前环境
  732. const env = isBrowserEnvironment();
  733. // ios环境下 直接使用浏览器api返回上一页
  734. if(env.isBrowser && !env.isMiniProgramWebview && env.isIPhone && env.isTopWindow) {
  735. // 上面的方法执行未生效就走这里
  736. if (window.history.length > 1) {
  737. return window.history.back();
  738. }
  739. }
  740. uni && uni.reLaunch({ url: '/pages/index/index' });
  741. },
  742. // 发送业务指令通道消息
  743. sendWsCommand(data) {
  744. if(this.doConnectDirectivesWs.readyState === 1) {
  745. this.doConnectDirectivesWs.send(JSON.stringify(data));
  746. return true;
  747. }
  748. return false;
  749. },
  750. // 初始化日志上报实例
  751. initLogReport() {
  752. // 初始化日志上报实例
  753. this.logReportObj = new logReport({ request: this.$axios });
  754. uni.getEnv((res) => {
  755. // 设置上报参数
  756. this.logReportObj.setParams({ clientType: Object.keys(res)[0] });
  757. })
  758. },
  759. }
  760. }
  761. </script>
  762. <style lang="scss" scoped>
  763. html{
  764. background-color: #000;
  765. }
  766. // 动态生成 从 0 到 100px 的样式
  767. @for $i from 0 through 100 {
  768. .mb-#{$i} {
  769. margin-bottom: #{$i}px;
  770. }
  771. .mt-#{$i} {
  772. margin-top: #{$i}px;
  773. }
  774. .ml-#{$i} {
  775. margin-left: #{$i}px;
  776. }
  777. .mr-#{$i} {
  778. margin-right: #{$i}px;
  779. }
  780. }
  781. $-radeus-12: 12px;
  782. $-bg-yellow: rgb(255, 253, 241);
  783. .rtc-page{
  784. position: relative;
  785. font-size: 14px;
  786. .video-wrapper{
  787. position: relative;
  788. }
  789. }
  790. .cover-bg{
  791. background-color: #000;
  792. }
  793. #foot-menu-wrap{
  794. border-width: 0px;
  795. position: absolute;
  796. left: 0px;
  797. bottom: 0px;
  798. width: 100%;
  799. // height: 40px; // 三大功能键高度,通过vue动态添加
  800. background: inherit;
  801. background-color: rgba(0, 12, 23, 1);
  802. border: none;
  803. border-radius: 0px;
  804. -moz-box-shadow: none;
  805. -webkit-box-shadow: none;
  806. box-shadow: none;
  807. z-index: 1;
  808. display: flex;
  809. justify-content: space-evenly;
  810. align-items: center;
  811. color: #fff;
  812. }
  813. </style>