WXtrialInterfaceCopy.js 47 KB

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