WXtrialInterface.js 40 KB

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