WXtrialInterface.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. console.log(res.status, logReportObj.RESPONSE_CODE[res.status])
  598. // 设置日志 推流状态为失败,和链接状态
  599. logReportObj.setParams({plugFowStatus: 2, linkWay: logReportObj.RESPONSE_CODE[res.status] || 0});
  600. // 日志上报
  601. logReportObj.collectLog(
  602. `接口获取数据失败:
  603. url: /api/resources/user/cloud/connect
  604. method: post
  605. 参数: ${JSON.stringify({ userCardId })}
  606. 响应: ${JSON.stringify(res)}`
  607. );
  608. return;
  609. }
  610. const data = res.data;
  611. console.log('videoType', data.videoCode, data.videoCode.toLowerCase(), logReportObj.VIDEO_TYPE[data.videoCode.toLowerCase()])
  612. // 设置上报参数
  613. logReportObj.setParams({videoType: data.videoCode.toLowerCase(), resourceId: data.resourceId});
  614. switch (res.status) {
  615. case 0:
  616. getUserCardInfoRequestNum = 1
  617. // 不支持webRTC跳转到指定的页面
  618. if (!res.data.isWebrtc) {
  619. // 关闭日志上报
  620. logReportObj.destroy();
  621. // 跳转指定页面
  622. location.replace(`${location.origin}/h5/webRtcYJ/WXtrialInterface.html${location.search}`)
  623. return
  624. }
  625. if (!this.isSupportRtc) {
  626. // 设置日志 推流状态为失败
  627. logReportObj.setParams({plugFowStatus: 2});
  628. // 日志上报
  629. logReportObj.collectLog(`${+isWeixin ? '微信小程序' : ''}当前版本暂不支持使用`);
  630. Dialog.alert({
  631. title: '提示',
  632. message: `${+isWeixin ? '微信小程序' : ''}当前版本暂不支持使用,可下载谷歌浏览器或双子星客户端进行使用`,
  633. confirmButtonText: '确定',
  634. confirmButtonColor: '#3cc51f',
  635. beforeClose: (action, done) => {
  636. this.exit()
  637. done()
  638. }
  639. })
  640. return
  641. }
  642. // webRtc连接,需获取连接中转地址
  643. if (res.data.webrtcNetworkAnalysis) {
  644. // 如果有网络分析的请求地址, 则请求,否则失败
  645. const webrtcNetworkAnalysisReq = await request.get(res.data.webrtcNetworkAnalysis);
  646. if (webrtcNetworkAnalysisReq !== null && webrtcNetworkAnalysisReq.success) {
  647. if (webrtcNetworkAnalysisReq.data) {
  648. // 保存获取的连接地址到上个请求的响应中, 方便后面使用
  649. res.data.webrtcNetwork = webrtcNetworkAnalysisReq.data;
  650. // 设置上报参数
  651. logReportObj.setParams({transferServerIp: webrtcNetworkAnalysisReq.data});
  652. }else{
  653. // 设置上报参数
  654. logReportObj.setParams({linkWay: 4, plugFowStatus: 2});
  655. // 日志上报
  656. logReportObj.collectLog(
  657. `webRtc连接,获取中转地址成功,但返回数据为空:
  658. url: ${res.data.webrtcNetworkAnalysis}
  659. method: get
  660. 参数: 无
  661. 响应: ${JSON.stringify(webrtcNetworkAnalysisReq)}`
  662. );
  663. }
  664. }else{
  665. // 设置上报参数
  666. logReportObj.setParams({linkWay: 4, plugFowStatus: 2});
  667. // 日志上报
  668. logReportObj.collectLog(
  669. `webRtc连接,获取中转地址失败:
  670. url: ${res.data.webrtcNetworkAnalysis}
  671. method: get
  672. 参数: 无
  673. 响应: ${JSON.stringify(webrtcNetworkAnalysisReq)}`
  674. );
  675. }
  676. }else{
  677. // 设置上报参数
  678. logReportObj.setParams({linkWay: 4, plugFowStatus: 2});
  679. // 日志上报
  680. logReportObj.collectLog(
  681. `webRtc连接,获取请求中转地址为空:
  682. url: /api/resources/user/cloud/connect
  683. method: post
  684. 参数: ${JSON.stringify({ userCardId })}
  685. 响应: ${JSON.stringify(res)}`
  686. );
  687. }
  688. // 如果没有获取到连接地址, 则失败
  689. if(!res.data.webrtcNetwork) {
  690. Dialog.alert({
  691. title: '提示',
  692. message: '访问失败,请稍后重试',
  693. confirmButtonText: '确定',
  694. confirmButtonColor: '#3cc51f',
  695. beforeClose: (action, done) => {
  696. this.exit()
  697. done()
  698. }
  699. })
  700. return;
  701. }
  702. this.userCardInfoData = res.data
  703. // let ms = + new Date() - this.obtainCardInfoStartTime
  704. this.connectWebRtc()
  705. return
  706. case 5200:
  707. case 5220:
  708. case 5203:
  709. case 5204:
  710. if (res.status === 5200) {
  711. reconnect.bind(this)()
  712. return
  713. }
  714. Toast(statusTips[res.status])
  715. break
  716. default:
  717. // 设置上报参数
  718. logReportObj.setParams({linkWay: logReportObj.RESPONSE_CODE[res.status] || 0});
  719. // 日志上报
  720. logReportObj.collectLog(statusTips[res.status] ||
  721. `webRtc连接,获取请求中转地址返回异常:
  722. url: /api/resources/user/cloud/connect
  723. method: post
  724. 参数: ${JSON.stringify({ userCardId })}
  725. 响应: ${JSON.stringify(res)}`
  726. );
  727. Toast('画面异常,请重新进入')
  728. break
  729. }
  730. setTimeout(() => {
  731. this.exit()
  732. }, 3000)
  733. } catch (error) {
  734. }
  735. }).catch((error) => {
  736. // 设置上报参数
  737. logReportObj.setParams({linkWay: 4, plugFowStatus: 2});
  738. // 日志上报
  739. logReportObj.collectLog(
  740. `接口获取数据失败:
  741. url: /api/resources/user/cloud/connect
  742. method: post
  743. 参数: ${JSON.stringify({ userCardId })}
  744. 响应: ${JSON.stringify(error)}`
  745. );
  746. })
  747. // 重连
  748. function reconnect() {
  749. // 重连6次结束
  750. if (getUserCardInfoRequestNum > 6) {
  751. Toast('网络异常,请稍后重试')
  752. clearTimeout(getUserCardInfoTimerInterval)
  753. setTimeout(() => {
  754. this.exit()
  755. }, 3000)
  756. return
  757. }
  758. // 重连
  759. getUserCardInfoTimerInterval = setTimeout(() => {
  760. this.getUserCardInfo()
  761. getUserCardInfoRequestNum++
  762. }, 3000)
  763. }
  764. },
  765. // 超过指定触碰时间是否提示关闭链接
  766. pushflowPopup() {
  767. request.get('/api/public/v5/pushflow/popup').then(res => {
  768. if (res.success) {
  769. this.isFiringNoOperationSetTimeout = res.data
  770. this.noOperationSetTimeout()
  771. }
  772. })
  773. },
  774. // 退出功能
  775. exit() {
  776. // 关闭日志上报
  777. logReportObj.destroy();
  778. this.engine.disconnect && this.engine.disconnect();
  779. this.doConnectDirectivesWs && this.doConnectDirectivesWs.close()
  780. uni.reLaunch({
  781. url: '/pages/index/index'
  782. });
  783. },
  784. // 不触碰屏幕显示退出链接弹窗
  785. noOperationSetTimeout(key) {
  786. if (!this.isFiringNoOperationSetTimeout) return
  787. clearTimeout(noOperationSetTimeoutTimeInterval)
  788. if (key === 'cancel') {
  789. clearInterval(noOperationSetIntervalTimeInterval)
  790. this.noOperationSetTimeoutTimeVisible = false
  791. this.noOperationSetTimeout()
  792. return
  793. }
  794. noOperationSetTimeoutTimeInterval = setTimeout(() => {
  795. let index = 9
  796. this.confirmButtonText = '退出(10秒)'
  797. this.noOperationSetTimeoutTimeVisible = true
  798. noOperationSetIntervalTimeInterval = setInterval(() => {
  799. this.confirmButtonText = `退出${index ? `(${index}秒)` : ''}`
  800. index--
  801. if (index < 0) {
  802. this.noOperationSetTimeout('cancel')
  803. this.exit()
  804. }
  805. }, 1000)
  806. }, 300000)
  807. },
  808. // 获取云机剩余时长
  809. async getResidueTime() {
  810. clearInterval(countdownTimeInterval)
  811. const { userCardType, isShowCountdown, isShowRule } = this.parametersData
  812. const { userCardId } = this.userCardInfoData
  813. if (![1, 2, 3].includes(+userCardType)) return
  814. const res = await request.get(`/api/resources/yearMember/getResidueTime?userCardId=${userCardId}`)
  815. let time = res.data;
  816. if (!res.status) {
  817. this.countdownTime = residueTimeStamp(time)
  818. await request.get(`/api/resources/yearMember/startTime?userCardId=${userCardId}`)
  819. if (+isShowCountdown) this.timingVisible = true
  820. if (+isShowRule) this.billingRulesVisible = true
  821. countdownTimeInterval = setInterval(() => {
  822. if (time <= 0) {
  823. clearInterval(countdownTimeInterval)
  824. this.downline()
  825. return
  826. }
  827. time--
  828. this.countdownTime = residueTimeStamp(time)
  829. }, 1000)
  830. }
  831. },
  832. // 关闭倒计时弹窗
  833. handlecountdownTimeClose() {
  834. const { userCardId } = this.userCardInfoData
  835. request.get(`/api/resources/yearMember/closeRemind?userCardId=${userCardId}`).then(res => {
  836. if (!res.status) {
  837. clearInterval(countdownTimeInterval)
  838. this.timingVisible = false
  839. return
  840. }
  841. Toast(res.msg);
  842. })
  843. },
  844. // 退出并下机
  845. downline(fun = () => { }) {
  846. const { userCardId } = this.userCardInfoData
  847. request.get(`/api/resources/yearMember/downline?userCardId=${userCardId}`).then(res => {
  848. if (!res.status) {
  849. fun(true)
  850. // 通信给h5项目告知是退出并下机
  851. parent.postMessage(
  852. {
  853. type: 'exit',
  854. },
  855. '*',
  856. );
  857. uni.postMessage({
  858. data: {
  859. type: 'exit'
  860. }
  861. });
  862. this.exit()
  863. return
  864. }
  865. fun(false)
  866. Toast(res.msg);
  867. })
  868. },
  869. // 获取推荐列表
  870. getRecommend() {
  871. const { userCardId } = this.userCardInfoData
  872. request.get(`/api/public/v1/market/get/recommend?userCardId=${userCardId}`).then(res => {
  873. if (!res.status) {
  874. this.billingRulesVisible = false
  875. this.recommendList = res.data
  876. this.recommendList.length && (this.applyRecommendVisible = true)
  877. }
  878. })
  879. },
  880. // 下载apk
  881. downAndInstallApk({ downloadUrl: apkUrl, id: taskUid }) {
  882. this.doConnectDirectivesWs.send(JSON.stringify({
  883. type: 'downAndInstallApk',
  884. data: {
  885. apkUrl,
  886. taskUid
  887. },
  888. }))
  889. },
  890. // 移开手指时会发生的回调
  891. touchendRtcMediaPlayer(event) {
  892. this.engine.touchClick && this.engine.touchClick(event, 1, true)
  893. this.noOperationSetTimeout()
  894. },
  895. // 返回、主页、任务器
  896. footerBtnFun(key) {
  897. this.engine[key] && this.engine[key]()
  898. this.noOperationSetTimeout()
  899. },
  900. // 获取初始化尺寸
  901. getInitSize() {
  902. // 高度、悬浮球相关配置
  903. this.height = window.innerHeight
  904. this.width = window.innerWidth
  905. this.$nextTick(() => {
  906. // 云机画面宽高
  907. let layoutView = document.querySelector('.layout-view')
  908. this.layoutViewWidth = layoutView.offsetWidth
  909. this.layoutViewHeight = layoutView.offsetHeight
  910. })
  911. },
  912. // 音量
  913. volumeControl(value) {
  914. this.engine.ExexuteKeyBoard && this.engine.ExexuteKeyBoard(value)
  915. this.$refs.rtcMediaPlayer && (this.$refs.rtcMediaPlayer.muted = false)
  916. },
  917. // 初始化日志上报实例
  918. initLogReport() {
  919. let clientType;
  920. uni.getEnv((res)=>{
  921. console.log('当前环境:', res, );
  922. clientType = Object.entries(res)?.[0];
  923. })
  924. // 初始化日志上报实例
  925. logReportObj = new logReport({request});
  926. // 设置上报参数
  927. logReportObj.setParams({clientType: clientType[0]});
  928. }
  929. }
  930. })
  931. function playOnBtn() {
  932. const { isTips } = this.parametersData;
  933. Dialog.alert({
  934. title: '提示',
  935. message: `${+isTips ? '开始' : '继续'}使用云手机`,
  936. confirmButtonText: '确定',
  937. confirmButtonColor: '#3cc51f',
  938. beforeClose: (action, done) => {
  939. if (action === 'confirm') {
  940. this.isShowVideo = true
  941. Toast.clear();
  942. this.$refs.rtcMediaPlayer.play()
  943. setTimeout(() => {
  944. this.doConnectDirectives()
  945. this.definitionFun(this.definitionValue)
  946. this.pushflowPopup()
  947. this.getResidueTime()
  948. done()
  949. })
  950. }
  951. }
  952. });
  953. }
  954. // 获取URL参数
  955. function getParameters() {
  956. let arr = location.search.split('?')
  957. let obj = {}
  958. if (arr[1]) {
  959. arr = arr[1].split('&')
  960. arr.forEach(item => {
  961. let [key, value = ''] = item.split('=')
  962. obj[key] = value
  963. })
  964. }
  965. return obj
  966. }
  967. // 倒计时处理的时间
  968. function residueTimeStamp(value) {
  969. let theTime = value;//秒
  970. let middle = 0;//分
  971. let hour = 0;//小时
  972. if (theTime > 59) {
  973. middle = parseInt(theTime / 60);
  974. theTime = parseInt(theTime % 60);
  975. }
  976. if (middle > 59) {
  977. hour = parseInt(middle / 60);
  978. middle = parseInt(middle % 60);
  979. }
  980. theTime < 10 ? theTime = '0' + theTime : theTime = theTime
  981. middle < 10 ? middle = '0' + middle : middle = middle
  982. hour < 10 ? hour = '0' + hour : hour = hour
  983. return hour + ':' + middle + ':' + theTime
  984. }