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, // SN号 必填
  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. isAllowedOpenCamera: true, // 是否允许打开摄像头
  210. callback: this.statusCallBack,//回调函数 必填
  211. };
  212. // 设置日志参数 推流质量
  213. logReportObj.setParams({imageQuality: 6000});
  214. // 初始化 SDK
  215. this.engine = new RtcEngineSDK(connection);
  216. this.engine.RtcEngine()
  217. },
  218. // webRTC状态回调
  219. statusCallBack(event) {
  220. if (event.type !== 'StreamStates') {
  221. // console.log("链接的状态", event, event.val);
  222. }
  223. switch (event.type) {
  224. case "screenChange":
  225. // 0:横屏 1:竖屏
  226. // console.log("屏幕方向变化事件:" + event.val);
  227. this.isLandscape = event.val === 0;
  228. break;
  229. case "wsState":
  230. // “TIMEOUT”:nats链接超时
  231. // success 链接成功
  232. const status = ["TIMEOUT", "failed"]
  233. if (status.includes(event.val)) {
  234. // 设置日志 推流状态为失败
  235. logReportObj.setParams({plugFowStatus: 2, linkWay: 0, linkEndTime: logReportObj.formatDate(new Date())});
  236. // 日志上报
  237. logReportObj.collectLog(
  238. `信令服务地址nats失败:
  239. url: ${this.engine.options.url}
  240. 消息: ${JSON.stringify(event)}`
  241. );
  242. Dialog.alert({
  243. title: '提示',
  244. message: '链接超时',
  245. confirmButtonText: '确定',
  246. confirmButtonColor: '#3cc51f',
  247. beforeClose: (action, done) => {
  248. this.exit()
  249. done()
  250. }
  251. })
  252. }
  253. break;
  254. case "rtcState":
  255. // “connected”:rtc链接成功 “failed”:rtc链接失败 “closed”:rtc链接关闭 “disconnected”:rtc链接超时
  256. // console.log(event.val, 'rtc链接成功状态')
  257. if (event.val === "connected") {
  258. // Toast.clear();
  259. // this.doConnectDirectives()
  260. // this.isShowVideo = true
  261. // this.$refs.rtcMediaPlayer.play()
  262. // let ms = +new Date - this.plugFlowStartTime
  263. // console.timeEnd('获取推流响应消耗时间:')
  264. // console.log(`获取推流响应消耗时间:${ms / 1000}秒`)
  265. // this.definitionFun(this.definitionValue)
  266. // this.pushflowPopup()
  267. // this.getResidueTime()
  268. // 设置日志 推流状态为成功
  269. let now = new Date();
  270. logReportObj.setParams({plugFowStatus: 1, linkWay: 1, timeConsuming: now.getTime() - logReportObj.timeStartTime, linkEndTime: logReportObj.formatDate(now)});
  271. // 日志上报
  272. logReportObj.collectLog(`推流成功`);
  273. playOnBtn.bind(this)()
  274. return
  275. }
  276. if (event.val === "connecting") return
  277. if (event.val === 'failed') {
  278. // 设置日志 推流状态为失败
  279. logReportObj.setParams({plugFowStatus: 2, linkWay: 1, linkEndTime: logReportObj.formatDate(new Date())});
  280. // 日志上报
  281. logReportObj.collectLog(
  282. `rtc链接失败:
  283. 消息: ${JSON.stringify(event)}`
  284. );
  285. }
  286. if(event.val === 'disconnected') {
  287. // 设置日志 推流状态为失败
  288. logReportObj.setParams({plugFowStatus: 2, linkWay: 1, linkEndTime: logReportObj.formatDate(new Date())});
  289. // 日志上报
  290. logReportObj.collectLog(
  291. `rtc链接超时:
  292. 消息: ${JSON.stringify(event)}`
  293. );
  294. }
  295. this.exit()
  296. break;
  297. case "AuthenticationStatus":
  298. // console.log(`鉴权${event.val === "success" ? '成功' : '失败'}`);
  299. if (event.val !== "success") {
  300. // 日志上报
  301. logReportObj.collectLog(
  302. `rtc鉴权失败:
  303. 消息: ${JSON.stringify(event)}`
  304. );
  305. }
  306. break;
  307. case "StreamStates":
  308. // “currentRoundTripTime”:延迟 “lostRate”:丢包率 “seconds_KBytes”:带宽 “framesPerSecond”:帧率
  309. // ballPosition.value = event.val
  310. // console.log(event.val)
  311. break;
  312. case 'videoResolution': // 云机视频分辨率
  313. // console.log(event.val, '分辨率')
  314. break
  315. case 'networkService': // 获取三网信息
  316. // console.log("三网信息:", event.val);
  317. break
  318. case 'networkServiceURL': // 获取三网信息
  319. // console.log("三网IP地址:", event.val);
  320. break
  321. }
  322. },
  323. // 悬浮球移动
  324. touchmoveLevitatedSphere(e) {
  325. let { pageX, pageY } = e.targetTouches[0]
  326. let min = 20
  327. let MaxPageX = this.width - 20
  328. let MaxPageY = this.height - 20
  329. pageX = pageX <= min ? min : (pageX >= MaxPageX ? MaxPageX : pageX)
  330. pageY = pageY <= min ? min : (pageY >= MaxPageY ? MaxPageY : pageY)
  331. this.levitatedSpherePositionData = {
  332. left: `${pageX}px`,
  333. top: `${pageY}px`,
  334. transform: 'translate(-50%, -50%)'
  335. }
  336. },
  337. touchendLevitatedSphere(e) {
  338. localStorage.setItem('levitatedSpherePositionData', JSON.stringify(this.levitatedSpherePositionData))
  339. },
  340. // 清晰度
  341. definitionFun(value) {
  342. this.definitionValue = value
  343. this.engine.makeBitrate && this.engine.makeBitrate(value)
  344. // 设置日志参数 推流质量
  345. logReportObj.setParams({imageQuality: value});
  346. localStorage.setItem('definitionValue', value)
  347. this.levitatedSphereVisible = false
  348. },
  349. // 修改分辨率
  350. resolutionRatio() {
  351. request.get('/api/resources/v5/machine/resolution/getResolvingPower', { params: { userCardId: this.parametersData.userCardId } }).then(res => {
  352. if (res.success) {
  353. this.resolutionRatioList = res.data.map(item => {
  354. item.height = item.high
  355. return item
  356. })
  357. this.levitatedSphereVisible = false
  358. this.resolutionRatioVisible = true
  359. }
  360. })
  361. },
  362. // 确定修改分辨率
  363. confirmResolution() {
  364. let { width, height, dpi: density } = this.phoneSize
  365. this.engine.makeResolution && this.engine.makeResolution({ width, height, density })
  366. this.resolutionRatioVisible = false
  367. },
  368. // 退出相关按钮操作
  369. exitFun(key) {
  370. switch (key) {
  371. case 'dormant':
  372. Dialog.alert({
  373. title: '提示',
  374. message: '确定退出云手机并下机',
  375. confirmButtonText: '确定',
  376. confirmButtonColor: '#3cc51f',
  377. showCancelButton: true,
  378. beforeClose: (action, done) => {
  379. if (action === 'cancel') done()
  380. if (action === 'confirm') {
  381. this.downline(done)
  382. }
  383. }
  384. })
  385. break;
  386. case 'shearplate':
  387. this.copyTextValue = ''
  388. pasteText().then(content => {
  389. typeof content !== 'boolean' ? this.openPasteboard(content) : this.copyTextVisible = true
  390. }, err => {
  391. this.copyTextVisible = true
  392. })
  393. break;
  394. case 'signout':
  395. this.exit()
  396. break;
  397. }
  398. },
  399. // 业务指令
  400. doConnectDirectives() {
  401. let { internetHttps, internetHttp, localIp, cardToken } = this.userCardInfoData
  402. const isWss = location.protocol === 'https:'
  403. let cUrl = `${isWss ? 'wss' : 'ws'}://${isWss ? internetHttps : internetHttp}/businessChannel?cardIp=${localIp}&token=${cardToken}&type=directives`
  404. this.doConnectDirectivesWs = new WebSocket(cUrl);
  405. this.doConnectDirectivesWs.binaryType = 'arraybuffer'
  406. clearInterval(doConnectDirectivesIntervalerPing)
  407. // 链接成功
  408. this.doConnectDirectivesWs.onopen = (e) => {
  409. doConnectDirectivesIntervalerPing = setInterval(() => {
  410. if (this.doConnectDirectivesWs.readyState === 1) {
  411. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'ping' }));
  412. } else {
  413. clearInterval(doConnectDirectivesIntervalerPing);
  414. }
  415. }, 3000)
  416. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'getVsStatus' }))
  417. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'bitRate', data: { bitRate: 1243000 } }))
  418. // 设置日志参数 推流质量
  419. logReportObj.setParams({imageQuality: 1243000});
  420. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'InputMethod', data: { type: 2 } }))
  421. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'getPhoneSize' }))
  422. }
  423. // 接受到的消息
  424. this.doConnectDirectivesWs.onmessage = res => {
  425. const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
  426. switch (result.type) {
  427. // 分辨率
  428. case 'getPhoneSize':
  429. case 'setPhoneSize':
  430. let data = JSON.parse(JSON.stringify(result.data))
  431. let { width, height } = data
  432. if (width > height) {
  433. data.width = height
  434. data.height = width
  435. }
  436. this.phoneSize = data
  437. break
  438. // 云机复制过来的文本
  439. case 'reProduceText':
  440. if (navigator.clipboard) {
  441. navigator.clipboard.writeText(result.data.text);
  442. }
  443. break
  444. case 'downAdnInstallRep':
  445. Toast(result.data.msg)
  446. break
  447. // 接受到这个消息就自动退出云机
  448. case 'exitPhone':
  449. this.exit()
  450. break
  451. }
  452. }
  453. // 链接报错的回调
  454. this.doConnectDirectivesWs.onerror = res => {
  455. // 设置日志 推流状态为失败
  456. logReportObj.setParams({plugFowStatus: 1, linkWay: 0, linkEndTime: logReportObj.formatDate(new Date())});
  457. // 日志上报
  458. logReportObj.collectLog(
  459. `业务指令通道报错:
  460. url: ${res.target.url}
  461. type: ${res.type}
  462. 消息: ${JSON.stringify(res)}`
  463. );
  464. clearInterval(doConnectDirectivesTimerInterval)
  465. if (doConnectDirectivesRequestNum > 6) {
  466. this.exit()
  467. return
  468. }
  469. doConnectDirectivesRequestNum++
  470. this.doConnectDirectives()
  471. }
  472. },
  473. // 粘贴版相关接口
  474. shearContent({ type, params, queryStr }) {
  475. let url = '/api/public/v5/shear/content'
  476. if (queryStr) url += queryStr
  477. return request[type](url, params)
  478. },
  479. // 清空全部、清除某条
  480. deletePasteVersion(ids) {
  481. if (!ids) {
  482. Dialog.alert({
  483. title: '提示',
  484. message: '确定清空剪贴板?',
  485. confirmButtonText: '确定',
  486. confirmButtonColor: '#3cc51f',
  487. showCancelButton: true,
  488. beforeClose: (action, done) => {
  489. if (action === 'cancel') done()
  490. if (action === 'confirm') {
  491. fun.bind(this)(done)
  492. }
  493. }
  494. })
  495. return
  496. }
  497. fun.bind(this)()
  498. function fun(callBack = () => { }) {
  499. this.shearContent({
  500. type: 'delete', queryStr: Qs.stringify(
  501. {
  502. ids: ids ? [ids] : this.pasteVersionList.map((v) => v.id),
  503. },
  504. { arrayFormat: 'repeat', addQueryPrefix: true },
  505. )
  506. }).then(res => {
  507. if (res.status === 0) {
  508. this.getPasteVersion()
  509. callBack(true)
  510. } else {
  511. callBack(false)
  512. Toast(res.msg)
  513. }
  514. }).catch(() => {
  515. callBack(false)
  516. })
  517. }
  518. },
  519. // 获取粘贴版数据
  520. getPasteVersion(callBack = () => { }) {
  521. this.shearContent({ type: 'get' }).then(res => {
  522. this.pasteVersionList = res.data
  523. callBack(true)
  524. }).catch(() => {
  525. callBack(false)
  526. }).finally(() => { })
  527. },
  528. // 复制弹窗是否关闭
  529. beforeCloseCopy(action, done) {
  530. if (action !== 'confirm') {
  531. // 获取剪切板
  532. this.getPasteVersion(() => {
  533. this.pasteVersionVisible = true
  534. this.levitatedSphereVisible = false
  535. done()
  536. })
  537. return
  538. }
  539. if (!this.copyTextValue) {
  540. Toast('请输入复制到剪切板的内容')
  541. done(false)
  542. return
  543. }
  544. this.openPasteboard(this.copyTextValue, done)
  545. },
  546. // 打开粘贴板
  547. async openPasteboard(content, callBack = () => { }) {
  548. this.shearContent({ type: 'post', params: { content } }).then().finally(() => {
  549. callBack()
  550. // 获取剪切板
  551. this.getPasteVersion(() => {
  552. this.pasteVersionVisible = true
  553. this.levitatedSphereVisible = false
  554. })
  555. })
  556. },
  557. // 复制粘贴某条数据
  558. copyPasteVersiontext(e) {
  559. clickCopyText(e, (event) => {
  560. this.doConnectDirectivesWs.send(JSON.stringify({
  561. type: 'cutting',
  562. data: {
  563. str: event.text,
  564. },
  565. }))
  566. Toast('复制成功')
  567. }, () => {
  568. Toast('复制失败')
  569. })
  570. },
  571. // 获取卡信息
  572. getUserCardInfo() {
  573. Toast.loading({
  574. duration: 0, // 持续展示 toast
  575. message: '数据加载中...',
  576. });
  577. this.obtainCardInfoStartTime = + new Date()
  578. let { userCardId } = this.parametersData
  579. userCardId = +userCardId
  580. const statusTips = {
  581. // 5200:RBD资源挂载中
  582. 5200: '网络异常,请稍后重试',
  583. // 入使用排队9.9,年卡
  584. 5220: '云手机正在一键修复中',
  585. 5203: '正在排队中,请稍等',
  586. // 9.9年卡连接异常,重新进入排队
  587. 5204: '云机异常,正在为你重新分配云机',
  588. 5228: '卡的网络状态为差',
  589. 5229: '接口返回链接信息缺失',
  590. }
  591. let { isWeixin } = this.parametersData;
  592. let clientType = +isWeixin ? 'wx' : undefined;
  593. // 设置上报参数
  594. logReportObj.setParams({userCardId});
  595. clientType && logReportObj.setParams({clientType});
  596. request.post('/api/resources/user/cloud/connect', { userCardId }).then(async res => {
  597. try {
  598. if (!res.success) {
  599. // 设置日志 推流状态为失败,和链接状态
  600. logReportObj.setParams({plugFowStatus: 2, linkWay: logReportObj.RESPONSE_CODE[res.status] || 0, linkEndTime: logReportObj.formatDate(new Date())});
  601. // 日志上报
  602. logReportObj.collectLog(
  603. `接口获取数据失败:
  604. url: /api/resources/user/cloud/connect
  605. method: post
  606. 参数: ${JSON.stringify({ userCardId })}
  607. 响应: ${JSON.stringify(res)}`
  608. );
  609. return;
  610. }
  611. const data = res.data;
  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, linkEndTime: logReportObj.formatDate(new Date())});
  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, linkEndTime: logReportObj.formatDate(new Date())});
  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, linkEndTime: logReportObj.formatDate(new Date())});
  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, linkEndTime: logReportObj.formatDate(new Date())});
  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. // 初始化日志上报实例
  920. logReportObj = new logReport({ request });
  921. uni.getEnv((res) => {
  922. // 设置上报参数
  923. logReportObj.setParams({clientType: Object.keys(res)[0]});
  924. })
  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. }