WXtrialInterface.js 44 KB

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