WXtrialInterface.js 41 KB

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