WXtrialInterfaceCopy.js 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. import request from './request.js'
  2. import { clickCopyText, pasteText } from './common.js'
  3. import logReport from './logReport.js'
  4. // 禁止双击缩放
  5. document.addEventListener('dblclick', function (e) {
  6. e.preventDefault();
  7. });
  8. // 添加监听 页面显示或隐藏 事件
  9. document.addEventListener('visibilitychange', visibilitychanged);
  10. // 监听 页面显示或隐藏 执行的函数
  11. function visibilitychanged() {
  12. // 获取当前环境
  13. const env = isBrowserEnvironment();
  14. // 获取当前页面的可见性状态
  15. const visibilityState = document.visibilityState;
  16. if (visibilityState === 'visible') {
  17. // 页面显示时的逻辑
  18. // 网页重载
  19. if (env.isBrowser && env.isTopWindow && env.isIPhone) {
  20. location.reload();
  21. }
  22. } else if (visibilityState === 'hidden') {
  23. // 页面隐藏时的逻辑
  24. // video.pause();
  25. } else if (visibilityState === 'prerender') {
  26. // 页面预渲染时的逻辑
  27. console.log('页面处于预渲染状态');
  28. } else if (visibilityState === 'unloaded') {
  29. // 页面即将卸载时的逻辑 移除监听
  30. document.removeEventListener('visibilitychange', visibilitychanged);
  31. }
  32. }
  33. /**
  34. * @description: 判断当前页面运行环境
  35. * @return {Object} 返回当前页面运行环境
  36. */
  37. function isBrowserEnvironment() {
  38. // 判断是否在浏览器环境中
  39. const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined';
  40. // 判断是否在微信环境中
  41. const isWechat = /MicroMessenger/i.test(navigator.userAgent);
  42. // 判断是否在微信小程序的 web-view 中
  43. const isMiniProgramWebview = isWechat && /miniProgram/i.test(navigator.userAgent);
  44. // 判断是否是 iPhone 设备
  45. const isIPhone = /iPhone/i.test(navigator.userAgent);
  46. // 判断是否是顶级窗口(不是嵌套在 iframe 中)目前只有ios的浏览器中才会是顶级窗口
  47. const isTopWindow = window.parent === window.self;
  48. return {
  49. isBrowser, // 是否在浏览器环境中
  50. isWechat, // 是否在微信环境中
  51. isMiniProgramWebview, // 是否在微信小程序的 web-view 中
  52. isIPhone, // 是否是 iPhone 设备
  53. isTopWindow, // 是否是顶级窗口
  54. };
  55. }
  56. /**
  57. * @description: 检查视频是否黑屏
  58. * @param {Number} threshold 阈值,根据需要调整 默认20
  59. * @return {Boolean} 返回是否为黑屏
  60. */
  61. function checkVideoBlackScreen(threshold = 20) { // 阈值,根据需要调整
  62. // 获取视频元素
  63. const video = document.getElementById('playerVideo');
  64. const canvas = document.createElement('canvas');
  65. const context = canvas.getContext('2d');
  66. canvas.width = video.videoWidth;
  67. canvas.height = video.videoHeight;
  68. // 绘制视频帧到画布上
  69. context.drawImage(video, 0, 0, canvas.width, canvas.height);
  70. // 获取图像数据
  71. const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
  72. const data = imageData.data;
  73. let totalBrightness = 0;
  74. // 遍历图像数据,计算亮度
  75. for (let i = 0; i < data.length; i += 4) {
  76. // 计算每个像素RGB(R:data[i], G:data[i + 1], B:data[i + 2])的亮度,这里使用简单的平均值
  77. const brightness = (data[i] + data[i + 1] + data[i + 2]) / 3;
  78. // 累加亮度值
  79. totalBrightness += brightness;
  80. }
  81. // 判断亮度是否低于阈值
  82. const averageBrightness = totalBrightness / (data.length / 4); // 计算平均亮度
  83. let isBlackScreen = averageBrightness < threshold;
  84. console.log('平均亮度', averageBrightness);
  85. // 释放资源
  86. canvas.remove();
  87. // 返回是否为黑屏
  88. return isBlackScreen;
  89. }
  90. const { Dialog, Toast } = vant
  91. Toast.setDefaultOptions({ duration: 2000 });
  92. // 从 CLOUD_GAME_SDK 结构中解构必要的函数和常量
  93. const RtcEngineSDK = window.rtc_sdk.CloudGameSdk
  94. // 业务通道定时标识
  95. let doConnectDirectivesIntervalerPing = null
  96. // 获取云机数据定时标识
  97. let getUserCardInfoTimerInterval = null
  98. let getUserCardInfoRequestNum = 1
  99. let doConnectDirectivesRequestNum = 1
  100. let doConnectDirectivesTimerInterval = null
  101. // 触碰间隔定时标识
  102. let noOperationSetTimeoutTimeInterval = null
  103. let noOperationSetIntervalTimeInterval = null
  104. // 倒计时定时标识
  105. let countdownTimeInterval = null
  106. // 日志上报实例
  107. let logReportObj = null;
  108. const app = new Vue({
  109. el: '#app',
  110. data: {
  111. // 底部按钮
  112. footerBtn: [{
  113. key: 'task',
  114. value: 187,
  115. img: '../static/img/wx/gengduo_icon.png'
  116. }, {
  117. key: 'home',
  118. value: 3,
  119. img: '../static/img/wx/home_icon.png'
  120. }, {
  121. key: 'onBack',
  122. value: 4,
  123. img: '../static/img/wx/fanhui_icon.png'
  124. }],
  125. // 宽高
  126. width: 0,
  127. height: 0,
  128. // webRtc实例
  129. engine: {},
  130. // 横竖屏幕 false是竖
  131. isLandscape: false,
  132. // 悬浮球位置
  133. levitatedSpherePositionData: {},
  134. // 右侧弹窗
  135. levitatedSphereVisible: false,
  136. // 清晰度数据
  137. definitionList: [{
  138. name: '自动',
  139. value: 2800
  140. }, {
  141. name: '高清',
  142. value: 2800
  143. }, {
  144. name: '标清',
  145. value: 1500,
  146. }, {
  147. name: '流畅',
  148. value: 1000,
  149. }],
  150. // 选中的清晰度
  151. definitionValue: '标清',
  152. // 分辨率
  153. resolutionRatioVisible: false,
  154. resolutionRatioList: [],
  155. // 需要用到的参数
  156. parametersData: {},
  157. // 屏幕分辨率
  158. phoneSize: {},
  159. // 业务指令通道实例
  160. doConnectDirectivesWs: null,
  161. // 粘贴版
  162. pasteVersionVisible: false,
  163. pasteVersionList: [],
  164. // 复制内容
  165. copyTextValue: '',
  166. copyTextVisible: false,
  167. // 卡数据
  168. userCardInfoData: {},
  169. // 是否显示计时
  170. timingVisible: false,
  171. // 计费规则
  172. billingRulesVisible: false,
  173. // 应用推荐
  174. applyRecommendVisible: false,
  175. // 是否是启动不操作自动退出云机功能
  176. isFiringNoOperationSetTimeout: false,
  177. // 超过指定触碰时间的弹窗
  178. noOperationSetTimeoutTimeVisible: false,
  179. // 超过指定触碰时间的弹窗文案
  180. confirmButtonText: '',
  181. // 云机剩余时长
  182. countdownTime: 0,
  183. // 是否支持webRTC
  184. isSupportRtc: !!(
  185. typeof RTCPeerConnection !== 'undefined' &&
  186. typeof RTCIceCandidate !== 'undefined' &&
  187. typeof RTCSessionDescription !== 'undefined'
  188. ),
  189. // 推荐列表
  190. recommendList: [],
  191. layoutViewWidth: null,
  192. layoutViewHeight: null,
  193. // 是否显示video
  194. isShowVideo: false,
  195. plugFlowStartTime: null,
  196. },
  197. created() {
  198. this.initConfig()
  199. },
  200. mounted() {
  201. // 初始化日志上报
  202. this.initLogReport();
  203. // 获取卡信息,并连接云机拉流
  204. this.getUserCardInfo();
  205. },
  206. // 销毁实例前
  207. beforeDestroy() {
  208. console.log('销毁实例前');
  209. },
  210. computed: {
  211. // 右侧弹框退出相关按钮
  212. exitList() {
  213. let arr = [{
  214. name: '剪贴版',
  215. key: "shearplate",
  216. img: '../static/img/wx/jianqieban_icon.png'
  217. }, {
  218. name: '退出',
  219. key: 'signout',
  220. img: '../static/img/wx/tuichu_icon.png'
  221. }]
  222. if ([1, 2, 3].includes(+this.parametersData.userCardType)) {
  223. arr.push({
  224. name: '退出并下机',
  225. key: 'dormant',
  226. img: '../static/img/wx/tuichu_icon.png'
  227. })
  228. }
  229. return arr
  230. },
  231. rtcMediaPlayerStyle() {
  232. let obj = {
  233. objectFit: "fill",
  234. width: `${this.layoutViewWidth}px`,
  235. height: `${this.layoutViewHeight}px`,
  236. }
  237. if (this.isLandscape) {
  238. obj = {
  239. width: `${this.layoutViewHeight}px`,
  240. height: `${this.layoutViewWidth}px`,
  241. transform: 'rotate(90deg)'
  242. }
  243. }
  244. return obj
  245. }
  246. },
  247. methods: {
  248. // 初始化
  249. initConfig() {
  250. // 获取窗口尺寸
  251. this.getInitSize();
  252. // 获取缓存悬浮球位置
  253. let levitatedSpherePositionData = localStorage.getItem('levitatedSpherePositionData');
  254. // 获取缓存清晰度
  255. let definitionValue = localStorage.getItem('definitionValue')
  256. // 悬浮球位置
  257. this.levitatedSpherePositionData = levitatedSpherePositionData ? JSON.parse(levitatedSpherePositionData) : { right: '15px', top: '15px' }
  258. // 清晰度
  259. this.definitionValue = definitionValue ? definitionValue : '标清'
  260. // 获取参数
  261. this.parametersData = getParameters()
  262. let { token, merchantSign } = this.parametersData
  263. // 给api增加需要的参数
  264. request.defaults.headers.Authorization = token;
  265. request.defaults.headers.versionname = '5.9.1';
  266. // 获取商户标识, 打开云机时必传, 用于日志上报
  267. request.defaults.headers.merchantSign = merchantSign;
  268. window.onresize = () => {
  269. console.log('窗口尺寸变化');
  270. this.getInitSize()
  271. }
  272. },
  273. // 连接webRTC
  274. connectWebRtc() {
  275. const MediaSdk = window.rtc_sdk.MediaSdk;
  276. const videoRef = document.getElementById("videoRef");
  277. this.plugFlowStartTime = +new Date()
  278. const { sn: topic, cardToken: authToken, internetIp, internetHttps, internetHttp, webrtcNetwork, webrtcTransferCmnet, webrtcTransferTelecom, webrtcTransferUnicom, videoCode } = this.userCardInfoData;
  279. const isWss = location.protocol === 'https:'
  280. const url = `${isWss ? 'wss://' : 'ws://'}${isWss ? internetHttps : internetHttp}/nats`;
  281. const ICEServerUrl = [
  282. // 统一使用三网解析地址
  283. { "CMNET": webrtcNetwork }, // 移动
  284. { 'CHINANET-GD': webrtcNetwork }, // 电信
  285. { 'UNICOM-GD': webrtcNetwork }, // 联通
  286. ];
  287. const connection = {
  288. mount: videoRef,
  289. displaySize: { // 整个页面的大小
  290. width: this.layoutViewWidth,
  291. height: this.layoutViewHeight,
  292. },
  293. topic, // SN号 必填
  294. url, //信令服务地址 必填
  295. ICEServerUrl,
  296. forwardServerAddress: '', // 转发服务器地址
  297. ip: internetIp, // 实例ip
  298. controlToken: authToken, // 控制token
  299. width: 720, // 推流视频宽度 必填
  300. height: 1280, // 推流视频高度 必填
  301. cardWidth: 0, // 云机系统分辨率 宽 必填
  302. cardHeight: 0, // 云机系统分辨率 高 必填
  303. cardDensity: 0, // 云机系统显示 密度 必填
  304. authToken, //拉流鉴权 token 必填
  305. quality: '标清',// 画质(码率) 超清 | 高清 | 标清 | 极速
  306. fps: 30, //必填
  307. videoCodec: videoCode, // 视频编码格式 必填
  308. videoCodecMethod: true, // 硬编true | 软编false
  309. isMuted: false, // 是否静音
  310. isAllowedOpenCamera: true, // 是否允许打开摄像头
  311. sendFollow: true, // 是否允许主控转发文本到实例
  312. callback: (event) => { }
  313. }
  314. // 设置日志参数 推流质量
  315. logReportObj.setParams({ imageQuality: 6000 }); // 6000在日志上报枚举中为高清
  316. // 初始化 SDK
  317. this.engine = new MediaSdk();
  318. console.log("初始化 SDK", this.engine);
  319. this.engine.RtcEngine(connection);
  320. // 监听回调方法
  321. this.eventCallbackFunction();
  322. },
  323. // webRTC状态回调监听回调方法
  324. eventCallbackFunction() {
  325. // TODO 查询屏幕方向未做
  326. const engine = this.engine;
  327. // 连接成功
  328. engine.on('CONNECT_SUCCESS', (r) => {
  329. console.log("webrtc连接成功====★★★★★", r);
  330. Toast.clear();
  331. // 设置日志 推流状态为成功
  332. let now = new Date();
  333. logReportObj.setParams({ plugFowStatus: 1, linkWay: 1, timeConsuming: now.getTime() - logReportObj.timeStartTime, linkEndTime: logReportObj.formatDate(now) });
  334. // 日志上报
  335. logReportObj.collectLog(`推流成功`);
  336. if (r.code === 1005) {
  337. // 重连
  338. if (this.getUserCardInfoRequestNum > 1) {
  339. engine.setControlAudio(true); // 设置音频
  340. engine.changeTouchMode(true);
  341. // 重连成功后重置请求次数
  342. this.getUserCardInfoRequestNum = 1;
  343. } else {
  344. engine.changeTouchMode(true);
  345. }
  346. }
  347. });
  348. engine.on('CONNECT_CLOSE', (r) => {
  349. console.log("webrtc关闭====★★★★★", r);
  350. });
  351. engine.on('CONNECT_ERROR', (r) => {
  352. console.log("webrtc异常状态====★★★★★", r);
  353. // 设置日志 推流状态为失败
  354. logReportObj.setParams({ plugFowStatus: 2, linkWay: 0, linkEndTime: logReportObj.formatDate(new Date()) });
  355. // 日志上报
  356. logReportObj.collectLog(
  357. `webrtc异常状态
  358. 消息: ${JSON.stringify(r)}`
  359. );
  360. Dialog.alert({
  361. title: '提示',
  362. message: '链接超时',
  363. confirmButtonText: '确定',
  364. confirmButtonColor: '#3cc51f',
  365. beforeClose: (action, done) => {
  366. this.exit()
  367. done()
  368. }
  369. })
  370. });
  371. engine.on('keyboardFeedbackBean', (r) => {
  372. console.log("打开键盘事件====★★★★★", r);
  373. });
  374. engine.on('RECEIVE_CHANNEL', (r) => {
  375. console.log("通道信息====★★★★★", r);
  376. });
  377. engine.on('RECEIVE_ICE', (r) => {
  378. console.log("三网地址====★★★★★", r);
  379. });
  380. engine.on('NETWORK_STATS', (r) => {
  381. // console.log("网络信息统计", r);
  382. });
  383. engine.on('RECEIVE_BITRATE_STATUS', (r) => {
  384. // code 100251 成功
  385. // code 100261 失败
  386. // code 100262 输入码率值异常
  387. // console.log("设置码率信息", r);
  388. });
  389. // 解码状态
  390. engine.on("DECODING_STATUS", (r) => {
  391. const statusMessages = {
  392. 10071: "rtc连接成功时间",
  393. 10072: "rtc连接失败时间",
  394. 10073: "鉴权成功时间",
  395. 1007: "渲染数据时间",
  396. 10074: "nats连接成功时间",
  397. 10075: "rtc连接失败时间",
  398. 10076: "rtc连接超时时间",
  399. 10077: "获取三网配置成功时间",
  400. 10078: "没有配置三网时间",
  401. 10079: "获取三网配置失败时间",
  402. 10080: "获取三网配置超时时间"
  403. };
  404. const message = statusMessages[r.code] || `未知的状态码: ${r.code}`;
  405. console.log(`${message}:`, r);
  406. });
  407. },
  408. // 悬浮球click事件
  409. onSphere(e) {
  410. this.levitatedSphereVisible = true
  411. e.preventDefault();
  412. },
  413. // 悬浮球按下事件
  414. onSphereDown(e) {
  415. // 给元素设置鼠标按下状态
  416. e.target.isMousedown = true;
  417. e.preventDefault();
  418. },
  419. // 悬浮球抬起事件
  420. onSphereUp(e) {
  421. // 给元素设置鼠标按下状态
  422. e.target.isMousedown = false;
  423. e.preventDefault();
  424. },
  425. // 悬浮球移动
  426. touchmoveLevitatedSphere(e) {
  427. // 过滤未按下时的移动事件
  428. if (e.type === 'mousemove' && !e.target.isMousedown) return
  429. let pageX, pageY;
  430. if (e.type === 'mousemove' && e.target.isMousedown) {
  431. pageX = e.pageX;
  432. pageY = e.pageY;
  433. } else if (e.type === 'touchmove') {
  434. // let { pageX, pageY } = e.targetTouches[0]
  435. pageX = e.targetTouches[0].pageX;
  436. pageY = e.targetTouches[0].pageY;
  437. }
  438. let min = 20
  439. let MaxPageX = this.width - 20
  440. let MaxPageY = this.height - 20
  441. pageX = pageX <= min ? min : (pageX >= MaxPageX ? MaxPageX : pageX)
  442. pageY = pageY <= min ? min : (pageY >= MaxPageY ? MaxPageY : pageY)
  443. this.levitatedSpherePositionData = {
  444. left: `${pageX}px`,
  445. top: `${pageY}px`,
  446. transform: 'translate(-50%, -50%)'
  447. }
  448. e.preventDefault();
  449. },
  450. touchendLevitatedSphere(e) {
  451. localStorage.setItem('levitatedSpherePositionData', JSON.stringify(this.levitatedSpherePositionData))
  452. },
  453. // 清晰度 画质
  454. definitionFun(item) {
  455. this.definitionValue = item.name
  456. const setBitrate = (item) => {
  457. const encoderConfig = {
  458. '自动': { width: 720, height: 1280, fps: 30 },
  459. '高清': { width: 720, height: 1280, fps: 30 },
  460. '标清': { width: 540, height: 960, fps: 25 },
  461. '流畅': { width: 450, height: 800, fps: 20 }
  462. };
  463. // 设置码率和是否允许自动
  464. this.engine?.setCustomBitrate(item.value, item.name === '自动');
  465. // 获取并设置编码器分辨率和帧率
  466. const config = encoderConfig[item.name];
  467. if (config) {
  468. this.engine?.setEncoderSize(config);
  469. }
  470. };
  471. // 设置自动码率
  472. setBitrate(item);
  473. // 设置日志参数 推流质量
  474. logReportObj.setParams({ imageQuality: item.name });
  475. localStorage.setItem('definitionValue', item.name)
  476. this.levitatedSphereVisible = false
  477. },
  478. // 修改分辨率
  479. resolutionRatio() {
  480. request.get('/api/resources/v5/machine/resolution/getResolvingPower', { params: { userCardId: this.parametersData.userCardId } }).then(res => {
  481. if (res.success) {
  482. this.resolutionRatioList = res.data.map(item => {
  483. item.height = item.high
  484. return item
  485. })
  486. this.levitatedSphereVisible = false
  487. this.resolutionRatioVisible = true
  488. }
  489. })
  490. },
  491. // 确定修改分辨率
  492. confirmResolution() {
  493. let { width, height, dpi: density } = this.phoneSize
  494. this.engine.makeResolution && this.engine.makeResolution({ width, height, density })
  495. this.resolutionRatioVisible = false
  496. },
  497. // 退出相关按钮操作
  498. exitFun(key) {
  499. console.log(key)
  500. switch (key) {
  501. case 'dormant':
  502. Dialog.alert({
  503. title: '提示',
  504. message: '确定退出云手机并下机',
  505. confirmButtonText: '确定',
  506. confirmButtonColor: '#3cc51f',
  507. showCancelButton: true,
  508. beforeClose: (action, done) => {
  509. if (action === 'cancel') done()
  510. if (action === 'confirm') {
  511. this.downline(done)
  512. }
  513. }
  514. })
  515. break;
  516. case 'shearplate':
  517. this.copyTextValue = ''
  518. pasteText().then(content => {
  519. typeof content !== 'boolean' ? this.openPasteboard(content) : this.copyTextVisible = true
  520. }, err => {
  521. this.copyTextVisible = true
  522. })
  523. break;
  524. case 'signout':
  525. this.exit()
  526. break;
  527. }
  528. },
  529. // 业务指令
  530. doConnectDirectives() {
  531. let { internetHttps, internetHttp, localIp, cardToken } = this.userCardInfoData
  532. const isWss = location.protocol === 'https:'
  533. let cUrl = `${isWss ? 'wss' : 'ws'}://${isWss ? internetHttps : internetHttp}/businessChannel?cardIp=${localIp}&token=${cardToken}&type=directives`
  534. this.doConnectDirectivesWs = new WebSocket(cUrl);
  535. this.doConnectDirectivesWs.binaryType = 'arraybuffer'
  536. clearInterval(doConnectDirectivesIntervalerPing)
  537. // 链接成功
  538. this.doConnectDirectivesWs.onopen = (e) => {
  539. doConnectDirectivesIntervalerPing = setInterval(() => {
  540. if (this.doConnectDirectivesWs.readyState === 1) {
  541. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'ping' }));
  542. } else {
  543. clearInterval(doConnectDirectivesIntervalerPing);
  544. }
  545. }, 3000)
  546. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'getVsStatus' }))
  547. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'bitRate', data: { bitRate: 1243000 } }))
  548. // 设置日志参数 推流质量
  549. logReportObj.setParams({ imageQuality: 1243000 });
  550. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'InputMethod', data: { type: 2 } }))
  551. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'getPhoneSize' }))
  552. }
  553. // 接受到的消息
  554. this.doConnectDirectivesWs.onmessage = res => {
  555. const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
  556. switch (result.type) {
  557. // 分辨率
  558. case 'getPhoneSize':
  559. case 'setPhoneSize':
  560. let data = JSON.parse(JSON.stringify(result.data))
  561. let { width, height } = data
  562. if (width > height) {
  563. data.width = height
  564. data.height = width
  565. }
  566. this.phoneSize = data
  567. break
  568. // 云机复制过来的文本
  569. case 'reProduceText':
  570. if (navigator.clipboard) {
  571. navigator.clipboard.writeText(result.data.text);
  572. }
  573. break
  574. case 'downAdnInstallRep':
  575. Toast(result.data.msg)
  576. break
  577. // 接受到这个消息就自动退出云机
  578. case 'exitPhone':
  579. this.exit()
  580. break
  581. }
  582. }
  583. // 链接报错的回调
  584. this.doConnectDirectivesWs.onerror = res => {
  585. // 设置日志 推流状态为失败
  586. logReportObj.setParams({ plugFowStatus: 1, linkWay: 0, linkEndTime: logReportObj.formatDate(new Date()) });
  587. // 日志上报
  588. logReportObj.collectLog(
  589. `业务指令通道报错:
  590. url: ${res.target.url}
  591. type: ${res.type}
  592. 消息: ${JSON.stringify(res)}`
  593. );
  594. clearInterval(doConnectDirectivesTimerInterval)
  595. if (doConnectDirectivesRequestNum > 6) {
  596. this.exit()
  597. return
  598. }
  599. doConnectDirectivesRequestNum++
  600. this.doConnectDirectives()
  601. }
  602. },
  603. // 粘贴版相关接口
  604. shearContent({ type, params, queryStr }) {
  605. let url = '/api/public/v5/shear/content'
  606. if (queryStr) url += queryStr
  607. return request[type](url, params)
  608. },
  609. // 清空全部、清除某条
  610. deletePasteVersion(ids) {
  611. if (!ids) {
  612. Dialog.alert({
  613. title: '提示',
  614. message: '确定清空剪贴板?',
  615. confirmButtonText: '确定',
  616. confirmButtonColor: '#3cc51f',
  617. showCancelButton: true,
  618. beforeClose: (action, done) => {
  619. if (action === 'cancel') done()
  620. if (action === 'confirm') {
  621. fun.bind(this)(done)
  622. }
  623. }
  624. })
  625. return
  626. }
  627. fun.bind(this)()
  628. function fun(callBack = () => { }) {
  629. this.shearContent({
  630. type: 'delete', queryStr: Qs.stringify(
  631. {
  632. ids: ids ? [ids] : this.pasteVersionList.map((v) => v.id),
  633. },
  634. { arrayFormat: 'repeat', addQueryPrefix: true },
  635. )
  636. }).then(res => {
  637. if (res.status === 0) {
  638. this.getPasteVersion()
  639. callBack(true)
  640. } else {
  641. callBack(false)
  642. Toast(res.msg)
  643. }
  644. }).catch(() => {
  645. callBack(false)
  646. })
  647. }
  648. },
  649. // 获取粘贴版数据
  650. getPasteVersion(callBack = () => { }) {
  651. this.shearContent({ type: 'get' }).then(res => {
  652. this.pasteVersionList = res.data
  653. callBack(true)
  654. }).catch(() => {
  655. callBack(false)
  656. }).finally(() => { })
  657. },
  658. // 复制弹窗是否关闭
  659. beforeCloseCopy(action, done) {
  660. if (action !== 'confirm') {
  661. // 获取剪切板
  662. this.getPasteVersion(() => {
  663. this.pasteVersionVisible = true
  664. this.levitatedSphereVisible = false
  665. done()
  666. })
  667. return
  668. }
  669. if (!this.copyTextValue) {
  670. Toast('请输入复制到剪切板的内容')
  671. done(false)
  672. return
  673. }
  674. this.openPasteboard(this.copyTextValue, done)
  675. },
  676. // 打开粘贴板
  677. async openPasteboard(content, callBack = () => { }) {
  678. this.shearContent({ type: 'post', params: { content } }).then().finally(() => {
  679. callBack()
  680. // 获取剪切板
  681. this.getPasteVersion(() => {
  682. this.pasteVersionVisible = true
  683. this.levitatedSphereVisible = false
  684. })
  685. })
  686. },
  687. // 复制粘贴某条数据
  688. copyPasteVersiontext(e) {
  689. clickCopyText(e, (event) => {
  690. this.doConnectDirectivesWs.send(JSON.stringify({
  691. type: 'cutting',
  692. data: {
  693. str: event.text,
  694. },
  695. }))
  696. Toast('复制成功')
  697. }, () => {
  698. Toast('复制失败')
  699. })
  700. },
  701. // 获取卡信息
  702. getUserCardInfo() {
  703. Toast.loading({
  704. duration: 0, // 持续展示 toast
  705. message: '数据加载中...',
  706. });
  707. // 从url中获取userCardId
  708. let { userCardId } = this.parametersData
  709. userCardId = +userCardId
  710. const statusTips = {
  711. // 5200:RBD资源挂载中
  712. 5200: '网络异常,请稍后重试',
  713. // 入使用排队9.9,年卡
  714. 5220: '云手机正在一键修复中',
  715. 5203: '正在排队中,请稍等',
  716. // 9.9年卡连接异常,重新进入排队
  717. 5204: '云机异常,正在为你重新分配云机',
  718. 5228: '卡的网络状态为差',
  719. 5229: '接口返回链接信息缺失',
  720. }
  721. let { isWeixin } = this.parametersData;
  722. let clientType = +isWeixin ? 'wx' : undefined;
  723. // 设置上报参数
  724. logReportObj.setParams({ userCardId });
  725. clientType && logReportObj.setParams({ clientType });
  726. // 获取卡信息
  727. request.post('/api/resources/user/cloud/connect', { userCardId }).then(async res => {
  728. try {
  729. if (!res.success) {
  730. // 设置日志 推流状态为失败,和链接状态
  731. logReportObj.setParams({ plugFowStatus: 2, linkWay: logReportObj.RESPONSE_CODE[res.status] || 0, linkEndTime: logReportObj.formatDate(new Date()) });
  732. // 日志上报
  733. logReportObj.collectLog(
  734. `接口获取数据失败:
  735. url: /api/resources/user/cloud/connect
  736. method: post
  737. 参数: ${JSON.stringify({ userCardId })}
  738. 响应: ${JSON.stringify(res)}`
  739. );
  740. return;
  741. }
  742. const data = res.data;
  743. // 设置上报参数
  744. logReportObj.setParams({ videoType: data.videoCode.toLowerCase(), resourceId: data.resourceId });
  745. switch (res.status) {
  746. case 0:
  747. getUserCardInfoRequestNum = 1
  748. // 不支持webRTC跳转到指定的页面
  749. if (!res.data.isWebrtc) {
  750. // 关闭日志上报
  751. logReportObj.destroy();
  752. // 跳转指定页面
  753. location.replace(`${location.origin}/h5/webRtcYJ/WXtrialInterface.html${location.search}`)
  754. return
  755. }
  756. if (!this.isSupportRtc) {
  757. // 设置日志 推流状态为失败
  758. logReportObj.setParams({ plugFowStatus: 2, linkEndTime: logReportObj.formatDate(new Date()) });
  759. // 日志上报
  760. logReportObj.collectLog(`${+isWeixin ? '微信小程序' : ''}当前版本暂不支持使用`);
  761. Dialog.alert({
  762. title: '提示',
  763. message: `${+isWeixin ? '微信小程序' : ''}当前版本暂不支持使用,可下载谷歌浏览器或客户端进行使用`,
  764. confirmButtonText: '确定',
  765. confirmButtonColor: '#3cc51f',
  766. beforeClose: (action, done) => {
  767. this.exit()
  768. done()
  769. }
  770. })
  771. return
  772. }
  773. // webRtc连接,需获取连接中转地址
  774. if (res.data.webrtcNetworkAnalysis) {
  775. // 如果有网络分析的请求地址, 则请求,则否失败
  776. const webrtcNetworkAnalysisReq = await request.get(res.data.webrtcNetworkAnalysis);
  777. if (webrtcNetworkAnalysisReq !== null && webrtcNetworkAnalysisReq.success) {
  778. if (webrtcNetworkAnalysisReq.data) {
  779. // 保存获取的连接地址到上个请求的响应中, 方便后面使用
  780. res.data.webrtcNetwork = webrtcNetworkAnalysisReq.data;
  781. // 设置上报参数
  782. logReportObj.setParams({ transferServerIp: webrtcNetworkAnalysisReq.data });
  783. } else {
  784. // 设置上报参数
  785. logReportObj.setParams({ linkWay: 4, plugFowStatus: 2 });
  786. // 日志上报
  787. logReportObj.collectLog(
  788. `webRtc连接,获取中转地址成功,但返回数据为空:
  789. url: ${res.data.webrtcNetworkAnalysis}
  790. method: get
  791. 参数: 无
  792. 响应: ${JSON.stringify(webrtcNetworkAnalysisReq)}`
  793. );
  794. }
  795. } else {
  796. // 设置上报参数
  797. logReportObj.setParams({ linkWay: 4, plugFowStatus: 2, linkEndTime: logReportObj.formatDate(new Date()) });
  798. // 日志上报
  799. logReportObj.collectLog(
  800. `webRtc连接,获取中转地址失败:
  801. url: ${res.data.webrtcNetworkAnalysis}
  802. method: get
  803. 参数: 无
  804. 响应: ${JSON.stringify(webrtcNetworkAnalysisReq)}`
  805. );
  806. }
  807. } else {
  808. // 设置上报参数
  809. logReportObj.setParams({ linkWay: 4, plugFowStatus: 2 });
  810. // 日志上报
  811. logReportObj.collectLog(
  812. `webRtc连接,获取请求中转地址为空:
  813. url: /api/resources/user/cloud/connect
  814. method: post
  815. 参数: ${JSON.stringify({ userCardId })}
  816. 响应: ${JSON.stringify(res)}`
  817. );
  818. }
  819. // 如果没有获取到连接地址, 则失败
  820. if (!res.data.webrtcNetwork) {
  821. Dialog.alert({
  822. title: '提示',
  823. message: '访问失败,请稍后重试',
  824. confirmButtonText: '确定',
  825. confirmButtonColor: '#3cc51f',
  826. beforeClose: (action, done) => {
  827. this.exit()
  828. done()
  829. }
  830. })
  831. return;
  832. }
  833. this.userCardInfoData = res.data
  834. // 进入连接云机准备阶段
  835. this.connectWebRtc();
  836. return
  837. case 5200:
  838. case 5220:
  839. case 5203:
  840. case 5204:
  841. Toast(statusTips[res.status]);
  842. // 设置上报参数
  843. logReportObj.setParams({ linkWay: logReportObj.RESPONSE_CODE[res.status] || 0, linkEndTime: logReportObj.formatDate(new Date()) });
  844. // 日志上报
  845. logReportObj.collectLog(statusTips[res.status] ||
  846. `webRtc连接,获取请求中转地址返回异常:
  847. url: /api/resources/user/cloud/connect
  848. method: post
  849. 参数: ${JSON.stringify({ userCardId })}
  850. 响应: ${JSON.stringify(res)}`
  851. );
  852. break
  853. default:
  854. // 设置上报参数
  855. logReportObj.setParams({ linkWay: logReportObj.RESPONSE_CODE[res.status] || 0, linkEndTime: logReportObj.formatDate(new Date()) });
  856. // 日志上报
  857. logReportObj.collectLog(statusTips[res.status] ||
  858. `webRtc连接,获取请求中转地址返回异常:
  859. url: /api/resources/user/cloud/connect
  860. method: post
  861. 参数: ${JSON.stringify({ userCardId })}
  862. 响应: ${JSON.stringify(res)}`
  863. );
  864. Toast('画面异常,请重新进入')
  865. break
  866. }
  867. setTimeout(() => {
  868. this.exit()
  869. }, 3000)
  870. } catch (error) {
  871. }
  872. }).catch((error) => {
  873. // 设置上报参数
  874. logReportObj.setParams({ linkWay: 4, plugFowStatus: 2, linkEndTime: logReportObj.formatDate(new Date()) });
  875. // 日志上报
  876. logReportObj.collectLog(
  877. `接口获取数据失败:
  878. url: /api/resources/user/cloud/connect
  879. method: post
  880. 参数: ${JSON.stringify({ userCardId })}
  881. 响应: ${JSON.stringify(error)}`
  882. );
  883. })
  884. // 重连
  885. function reconnect() {
  886. // 重连6次结束
  887. if (getUserCardInfoRequestNum > 6) {
  888. Toast('网络异常,请稍后重试')
  889. clearTimeout(getUserCardInfoTimerInterval)
  890. setTimeout(() => {
  891. this.exit()
  892. }, 3000)
  893. return
  894. }
  895. // 重连
  896. getUserCardInfoTimerInterval = setTimeout(() => {
  897. this.getUserCardInfo()
  898. getUserCardInfoRequestNum++
  899. }, 3000)
  900. }
  901. },
  902. // 超过指定触碰时间是否提示关闭链接
  903. pushflowPopup() {
  904. request.get('/api/public/v5/pushflow/popup').then(res => {
  905. if (res.success) {
  906. this.isFiringNoOperationSetTimeout = res.data
  907. this.noOperationSetTimeout()
  908. }
  909. })
  910. },
  911. // 退出功能
  912. exit() {
  913. // 关闭日志上报
  914. logReportObj.destroy();
  915. this.engine.disconnect && this.engine.disconnect();
  916. this.doConnectDirectivesWs && this.doConnectDirectivesWs.close()
  917. uni.reLaunch({
  918. url: '/pages/index/index'
  919. });
  920. // 上面的方法执行未生效就走这里
  921. if (window.history.length > 1) {
  922. window.history.back();
  923. }
  924. },
  925. // 不触碰屏幕显示退出链接弹窗
  926. noOperationSetTimeout(key) {
  927. if (!this.isFiringNoOperationSetTimeout) return
  928. clearTimeout(noOperationSetTimeoutTimeInterval)
  929. if (key === 'cancel') {
  930. clearInterval(noOperationSetIntervalTimeInterval)
  931. this.noOperationSetTimeoutTimeVisible = false
  932. this.noOperationSetTimeout()
  933. return
  934. }
  935. noOperationSetTimeoutTimeInterval = setTimeout(() => {
  936. let index = 9
  937. this.confirmButtonText = '退出(10秒)'
  938. this.noOperationSetTimeoutTimeVisible = true
  939. noOperationSetIntervalTimeInterval = setInterval(() => {
  940. this.confirmButtonText = `退出${index ? `(${index}秒)` : ''}`
  941. index--
  942. if (index < 0) {
  943. this.noOperationSetTimeout('cancel')
  944. this.exit()
  945. }
  946. }, 1000)
  947. }, 300000)
  948. },
  949. // 获取云机剩余时长
  950. async getResidueTime() {
  951. clearInterval(countdownTimeInterval)
  952. const { userCardType, isShowCountdown, isShowRule } = this.parametersData
  953. const { userCardId } = this.userCardInfoData
  954. if (![1, 2, 3].includes(+userCardType)) return
  955. const res = await request.get(`/api/resources/yearMember/getResidueTime?userCardId=${userCardId}`)
  956. let time = res.data;
  957. if (!res.status) {
  958. this.countdownTime = residueTimeStamp(time)
  959. await request.get(`/api/resources/yearMember/startTime?userCardId=${userCardId}`)
  960. if (+isShowCountdown) this.timingVisible = true
  961. if (+isShowRule) this.billingRulesVisible = true
  962. countdownTimeInterval = setInterval(() => {
  963. if (time <= 0) {
  964. clearInterval(countdownTimeInterval)
  965. this.downline()
  966. return
  967. }
  968. time--
  969. this.countdownTime = residueTimeStamp(time)
  970. }, 1000)
  971. }
  972. },
  973. // 关闭倒计时弹窗
  974. handlecountdownTimeClose() {
  975. const { userCardId } = this.userCardInfoData
  976. request.get(`/api/resources/yearMember/closeRemind?userCardId=${userCardId}`).then(res => {
  977. if (!res.status) {
  978. clearInterval(countdownTimeInterval)
  979. this.timingVisible = false
  980. return
  981. }
  982. Toast(res.msg);
  983. })
  984. },
  985. // 退出并下机
  986. downline(fun = () => { }) {
  987. const { userCardId } = this.userCardInfoData
  988. request.get(`/api/resources/yearMember/downline?userCardId=${userCardId}`).then(res => {
  989. if (!res.status) {
  990. fun(true)
  991. // 通信给h5项目告知是退出并下机
  992. parent.postMessage(
  993. {
  994. type: 'exit',
  995. },
  996. '*',
  997. );
  998. uni.postMessage({
  999. data: {
  1000. type: 'exit'
  1001. }
  1002. });
  1003. this.exit()
  1004. return
  1005. }
  1006. fun(false)
  1007. Toast(res.msg);
  1008. })
  1009. },
  1010. // 获取推荐列表
  1011. getRecommend() {
  1012. const { userCardId } = this.userCardInfoData
  1013. request.get(`/api/public/v1/market/get/recommend?userCardId=${userCardId}`).then(res => {
  1014. if (!res.status) {
  1015. this.billingRulesVisible = false
  1016. this.recommendList = res.data
  1017. this.recommendList.length && (this.applyRecommendVisible = true)
  1018. }
  1019. })
  1020. },
  1021. // 下载apk
  1022. downAndInstallApk({ downloadUrl: apkUrl, id: taskUid }) {
  1023. this.doConnectDirectivesWs.send(JSON.stringify({
  1024. type: 'downAndInstallApk',
  1025. data: {
  1026. apkUrl,
  1027. taskUid
  1028. },
  1029. }))
  1030. },
  1031. // 返回、主页、任务器
  1032. footerBtnFun(key) {
  1033. this.engine && this.engine.sendKey(key)
  1034. this.noOperationSetTimeout()
  1035. },
  1036. // 获取初始化尺寸
  1037. getInitSize() {
  1038. // 高度、悬浮球相关配置
  1039. this.height = window.innerHeight;
  1040. this.width = window.innerWidth;
  1041. this.$nextTick(() => {
  1042. // 云机画面宽高
  1043. let layoutView = document.querySelector('.layout-view')
  1044. // 获取视口宽度,webRTC需要做成16:9的画面
  1045. let currentWidth = layoutView.clientWidth;
  1046. let currentHeight = layoutView.clientHeight;
  1047. // 计算当前视口的宽高比
  1048. const currentRatio = currentWidth / currentHeight;
  1049. // 9:16 的目标比例
  1050. const targetRatio = 9 / 16;
  1051. console.log(`当前视口的宽高比: ${currentRatio}`);
  1052. // 判断当前视口的宽高比与目标比例的关系
  1053. if (currentRatio > targetRatio) {
  1054. // 当前视口的宽高比大于目标比例,说明宽度“过宽”,需要以高度为基准
  1055. console.log("当前视口宽度过宽,应以高度为基准调整宽度");
  1056. this.layoutViewWidth = currentHeight * targetRatio;
  1057. this.layoutViewHeight = currentHeight;
  1058. console.log(`1目标: 宽${this.layoutViewWidth},高${this.layoutViewHeight}`);
  1059. } else {
  1060. // 当前视口的宽高比小于目标比例,说明高度“过高”,需要以宽度为基准
  1061. console.log("当前视口高度过高,应以宽度为基准调整高度");
  1062. this.layoutViewHeight = currentWidth / targetRatio;
  1063. this.layoutViewWidth = currentWidth;
  1064. console.log(`2目标: 宽${this.layoutViewWidth},高${this.layoutViewHeight}`);
  1065. }
  1066. // 悬浮球位置设置为默认位置
  1067. this.levitatedSpherePositionData = { right: '15px', top: '15px' }
  1068. })
  1069. },
  1070. // 音量
  1071. volumeControl(value) {
  1072. this.engine.sendKey && this.engine.sendKey(value)
  1073. this.$refs.rtcMediaPlayer && (this.$refs.rtcMediaPlayer.muted = false)
  1074. },
  1075. // 初始化日志上报实例
  1076. initLogReport() {
  1077. // 初始化日志上报实例
  1078. logReportObj = new logReport({ request });
  1079. uni.getEnv((res) => {
  1080. // 设置上报参数
  1081. logReportObj.setParams({ clientType: Object.keys(res)[0] });
  1082. })
  1083. }
  1084. }
  1085. })
  1086. // 播放按钮点击事件
  1087. function playOnBtn() {
  1088. const { isTips } = this.parametersData;
  1089. Dialog.alert({
  1090. title: '提示',
  1091. message: `${+isTips ? '开始' : '继续'}使用云手机`,
  1092. confirmButtonText: '确定',
  1093. confirmButtonColor: '#3cc51f',
  1094. beforeClose: (action, done) => {
  1095. if (action === 'confirm') {
  1096. this.isShowVideo = true
  1097. Toast.clear();
  1098. this.$refs.rtcMediaPlayer.play()
  1099. setTimeout(() => {
  1100. this.doConnectDirectives()
  1101. this.pushflowPopup()
  1102. this.getResidueTime()
  1103. done()
  1104. })
  1105. }
  1106. }
  1107. });
  1108. }
  1109. // 获取URL参数
  1110. function getParameters() {
  1111. let arr = location.search.split('?')
  1112. let obj = {}
  1113. if (arr[1]) {
  1114. arr = arr[1].split('&')
  1115. arr.forEach(item => {
  1116. let [key, value = ''] = item.split('=')
  1117. obj[key] = value
  1118. })
  1119. }
  1120. return obj
  1121. }
  1122. // 倒计时处理的时间
  1123. function residueTimeStamp(value) {
  1124. let theTime = value;//秒
  1125. let middle = 0;//分
  1126. let hour = 0;//小时
  1127. if (theTime > 59) {
  1128. middle = parseInt(theTime / 60);
  1129. theTime = parseInt(theTime % 60);
  1130. }
  1131. if (middle > 59) {
  1132. hour = parseInt(middle / 60);
  1133. middle = parseInt(middle % 60);
  1134. }
  1135. theTime < 10 ? theTime = '0' + theTime : theTime = theTime
  1136. middle < 10 ? middle = '0' + middle : middle = middle
  1137. hour < 10 ? hour = '0' + hour : hour = hour
  1138. return hour + ':' + middle + ':' + theTime
  1139. }