WXtrialInterface.js 41 KB

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