App.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. <script>
  2. import config from '@/util/url.js';
  3. import HeartBeat from '@/util/HeartBeat.js'
  4. export default {
  5. globalData: {
  6. token: "",
  7. // 文本消息
  8. socketTask: null,
  9. // urlData: "wss://www.toreskj.com/api/api_gateway?method=control_center.real_time.im_message",
  10. urlData: config.wsUrl + "/api/api_gateway?method=control_center.real_time.im_message",
  11. is_open_socket: false, // 确保websocket是打开状态
  12. list: [],
  13. userId: null, // 用户ID
  14. // 即构
  15. video: null, //房间密码和token
  16. // 测试 - 心跳检测
  17. status: null, // websocket是否关闭
  18. lockReconnect: false, // 避免重复连接
  19. // timeout: 5000, // 多少秒执行监测
  20. timeout: 10000, // 多少秒执行监测
  21. timeoutObj: null, // 检测服务器端是否还活着
  22. reconnectTimeOutObj: null, // 重连之后多久再次重连
  23. // 测试
  24. app: [],
  25. // 消息发送加载
  26. msgSetTime: null,
  27. g_wakelock: null
  28. },
  29. onLoad() {},
  30. onLaunch: function() {
  31. console.log('启动了')
  32. HeartBeat.getInstance().destory();
  33. // App启动
  34. var that = this
  35. // #ifdef APP-PLUS
  36. this.wakeLock()
  37. // #endif
  38. // uni.getStorage({
  39. // key: 'session_key',
  40. // success: function(res) {
  41. // that.globalData.token = res.data
  42. // // console.log('登录成功了')
  43. // that.msgInit(); // 文本初始化
  44. // },
  45. // fail: function(err) {
  46. // console.log(err)
  47. // console.log('没有登录成功')
  48. // }
  49. // })
  50. },
  51. onShow: function() {
  52. var that = this
  53. this.$store.dispatch('updateTaskRecordRatio')
  54. // App展示在前台
  55. console.log('+++++++++++++++++++App Show-------------------------------------')
  56. // this.msgInit(); // 再进行请求
  57. uni.getStorage({
  58. key: 'session_key',
  59. success: function(res) {
  60. if(!res.data){
  61. return
  62. }
  63. that.globalData.token = res.data
  64. // console.log('登录成功了')
  65. console.log(res)
  66. that.msgInit(); // 文本初始化
  67. },
  68. fail: function(err) {
  69. console.log(err)
  70. console.log('没有登录成功')
  71. }
  72. })
  73. },
  74. onHide: function() {
  75. // App不再再展示在前台
  76. this.close(); // 关闭
  77. },
  78. methods: {
  79. // 实时通信 - 初始化
  80. msgInit() {
  81. console.log('进入了实时通信初始化=--------------------------', this.globalData.token)
  82. var that = this
  83. // 连接webscoket
  84. that.globalData.socketTask = uni.connectSocket({
  85. url: this.globalData.urlData + "&token=" + that.globalData.token,
  86. success(data) {
  87. // console.log("websocket连接中");
  88. }
  89. });
  90. // 发送消息 - 获取对话列表
  91. var obj = {
  92. 'action': 'list', // 动作标识,必填
  93. 'recv_user_id': '', // 接收人用户id, 非必填
  94. 'data': {}
  95. }
  96. that.globalData.socketTask.onOpen((res) => {
  97. console.log('websocket开启了')
  98. // 清除重连定时器
  99. // clearTimeout(that.globalData.reconnectTimeOutObj)
  100. // that.notReconnect()
  101. that.globalData.socketTask.send({
  102. data: JSON.stringify(obj),
  103. async success(res) {
  104. that.globalData.is_open_socket = true
  105. console.log("消息发送成功");
  106. uni.hideLoading(); // 关闭通信异常弹框
  107. },
  108. });
  109. that.start() // 开启心跳机制
  110. })
  111. // // 接收服务器返回的消息
  112. // // 注:只有连接正常打开中 ,才能正常收到消息
  113. that.globalData.socketTask.onMessage((res) => {
  114. // console.log("收到服务器内容:");
  115. var val = JSON.parse(res.data)
  116. console.warn('这是返回的内容---------', val)
  117. clearTimeout(that.globalData.msgSetTime); // 消息发送成功,清除发送失败定时器
  118. if (val.action == 'list') {
  119. clearTimeout(that.globalData.msgSetTime); // 消息发送成功,清除发送失败定时器
  120. console.log('这是发送人的ID', that.globalData.userId)
  121. var obj1 = {
  122. 'action': 'list', // 动作标识,必填
  123. 'recv_user_id': that.globalData.userId, // 接收人用户id, 非必填
  124. 'data': {
  125. 'msg_status': false, // 消息未读
  126. 'msg_info': '', // 发送消息
  127. }
  128. }
  129. that.globalData.socketTask.send({
  130. data: JSON.stringify(obj1),
  131. async success(res) {},
  132. });
  133. that.globalData.userId = null
  134. } else if (val.action == 'none') {
  135. console.log('进入了none', val)
  136. that.globalData.list = val.data
  137. // this.$store.state.list = val.data
  138. this.$store.commit('updateMessageList', val.data)
  139. } else if (val.action == 'recv_video') {
  140. console.warn('recv_video---------------- 1', val.data, this.$store.state
  141. .isVideoCallRefused)
  142. // if (this.$store.state.isVideoCallRefused) {
  143. // this.$store.commit('updateIsRefusedCall', false)
  144. // return
  145. // }
  146. // this.$store.state.video = val.data
  147. this.$store.commit('updateIsRefusedCall', false)
  148. if (this.$store.state.isVideoTalking) {
  149. // 占线中
  150. var obj = {
  151. 'action': 'occupy', // 动作标识,必填
  152. 'recv_user_id': val.data.user_id, // 接收人用户id, 非必填
  153. 'data': {}
  154. }
  155. this.globalData.socketTask.send({
  156. data: JSON.stringify(obj),
  157. async success(res) {
  158. console.warn('占线消息发送成功1111', obj)
  159. }
  160. });
  161. return
  162. }
  163. that.globalData.video = val.data
  164. uni.switchTab({
  165. url: '/pages/response/index',
  166. success(res) {
  167. console.warn(res, '--------------response index into room ')
  168. },
  169. fail(err) {
  170. console.error(err)
  171. },
  172. complete() {
  173. console.warn('--------------response index into room complete')
  174. }
  175. })
  176. this.$store.commit('updateVideoInfo', val.data)
  177. setTimeout(() => {
  178. console.log('跳转了')
  179. this.$store.getters.watchData;
  180. }, 1500)
  181. } else if (val.action == 'send_video_rsp') {
  182. console.warn('recv_video---------------- response', val.data)
  183. // if (this.$store.state.isVideoCallRefused) {
  184. // this.$store.commit('updateIsRefusedCall', false)
  185. // return
  186. // }
  187. this.$store.commit('updateIsRefusedCall', false)
  188. // if(this.)
  189. this.$store.commit('updateVideoSelfRoomInfo', val.data)
  190. console.warn('into romm ready ------------------', this.roomInfo)
  191. console.warn('into romm ------------------', this.roomInfo)
  192. this.$store.commit('updateTalkingStatus', true)
  193. uni.navigateTo({
  194. url: '/pages/response/video?videoObj=' + JSON.stringify(val.data),
  195. success(res) {
  196. console.warn(res, '-------------- into room ')
  197. },
  198. fail(err) {
  199. console.error(err)
  200. },
  201. complete() {
  202. console.warn('-------------- into room complete')
  203. }
  204. })
  205. } else if (val.action == 'reject_video_rsp') {
  206. console.warn('reject_video_rsp', '挂断 拒接')
  207. // 被拒绝后挂断视频通话
  208. this.$store.commit('updateIsRefusedCall', true)
  209. } else if (val.action == 'occupy_rsp') {
  210. console.warn('----------------------- is refused')
  211. // 占线中,挂断发起通话
  212. this.$store.commit('updateOccupyedStatus',true);
  213. this.$store.commit('updateIsRefusedCall', true)
  214. } else if (val.action == 'ok') {
  215. this.start(); // 心跳机制
  216. } else if (val.action == 'error') {
  217. console.log('action error')
  218. if (val.code == 403 || val.data && val.data.code == 403) {
  219. this.close();
  220. uni.setStorageSync('session_key', '');
  221. this.globalData.token = '';
  222. if (!this.$store.state.isInLoginPage) {
  223. uni.$u.totast && uni.$u.totast(val.data.data && val.data.data.error_info || '用户在其他地方登陆,请重新登陆')
  224. setTimeout(() => {
  225. uni.reLaunch({
  226. url: "/pages/login/login"
  227. })
  228. }, 2000)
  229. }
  230. }
  231. }
  232. // this.reset();
  233. // console.log('消息可正常接收');
  234. });
  235. // 连接断开
  236. // 如果希望websocket连接一直保持,在close或者error上绑定重新连接方法。
  237. this.globalData.socketTask.onClose((res) => {
  238. console.warn(res, '连接关闭');
  239. clearTimeout(this.globalData.timeoutObj);
  240. setTimeout(() => {
  241. that.reconnect();
  242. }, 5000)
  243. })
  244. // 连接失败
  245. that.globalData.socketTask.onError((res) => {
  246. console.log(res, '连接错误');
  247. // uni.showLoading({
  248. // title: "通信异常,连接中..."
  249. // })
  250. clearTimeout(this.globalData.timeoutObj);
  251. setTimeout(() => {
  252. that.reconnect();
  253. }, 5000)
  254. })
  255. },
  256. // 心跳机制
  257. start() {
  258. var that = this
  259. this.globalData.timeoutObj = setTimeout(() => {
  260. //这里发送一个心跳,后端收到后,返回一个心跳消息,
  261. //onmessage拿到返回的心跳就说明连接正常
  262. var obj = {
  263. 'action': 'keepalive', // 动作标识,必填
  264. 'type': 'App',
  265. 'recv_user_id': '', // 接收人用户id, 非必填
  266. 'data': {
  267. msg_status: false,
  268. msg_info: "",
  269. }
  270. }
  271. that.globalData.socketTask.send({
  272. data: JSON.stringify(obj),
  273. async success(res) {
  274. that.globalData.is_open_socket = true
  275. // console.log('消息发送成功1111')
  276. }
  277. });
  278. console.log('进入心跳机制了', that.globalData.socketTask)
  279. let ws_temp = null
  280. ws_temp = that.globalData.socketTask
  281. that.globalData.socketTask = ws_temp
  282. ws_temp = null
  283. }, this.globalData.timeout)
  284. },
  285. // 清除心跳机制
  286. reset() {
  287. // 清除定时器重新发送一个心跳信息
  288. // clearTimeout(this.globalData.timeoutObj);
  289. clearTimeout(this.globalData.timeoutObj);
  290. this.start();
  291. },
  292. // 重连
  293. reconnect() {
  294. // 防止多个方法调用,多处重连
  295. if (this.lockReconnect) {
  296. return;
  297. };
  298. if(!this.globalData.token){
  299. return
  300. }
  301. this.lockReconnect = true;
  302. console.log('准备重连');
  303. //没连接上会一直重连,设置延迟避免请求过多
  304. this.globalData.reconnectTimeOutObj = setTimeout(() => {
  305. // 重新连接
  306. this.msgInit()
  307. console.log('正在重新连接')
  308. this.lockReconnect = false;
  309. }, 4000);
  310. },
  311. // 清除重连
  312. notReconnect() {
  313. clearTimeout(this.globalData.reconnectTimeOutObj)
  314. },
  315. // 手动关闭
  316. close() {
  317. var that = this
  318. console.log('已经手动关闭了')
  319. that.globalData.socketTask.close()
  320. that.globalData.socketTask = null
  321. clearTimeout(that.globalData.timeoutObj);
  322. clearTimeout(that.globalData.reconnectTimeOutObj);
  323. uni.hideLoading(); // 关闭通信异常弹框
  324. },
  325. //允许程序后台运行,以持续获取GPS位置
  326. wakeLock() {
  327. //Android
  328. const main = plus.android.runtimeMainActivity();
  329. console.warn('--------- walk lock------------ dsd', main)
  330. const Context = plus.android.importClass("android.content.Context");
  331. const PowerManager = plus.android.importClass("android.os.PowerManager");
  332. const pm = main.getSystemService(Context.POWER_SERVICE);
  333. this.g_wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ANY_NAME");
  334. this.g_wakelock.acquire();
  335. },
  336. //结束程序后台运行
  337. releaseWakeLock() {
  338. if (this.g_wakelock != null && this.g_wakelock.isHeld()) {
  339. this.g_wakelock.release();
  340. this.g_wakelock = null;
  341. }
  342. },
  343. }
  344. }
  345. </script>
  346. <!-- // App.vue文件 中首行的位置引入,注意给style标签加入lang="scss"属性 -->
  347. <style lang="scss">
  348. @import './common/zego-nvue.css';
  349. /* 注意要写在第一行,同时给style标签加入lang="scss"属性 */
  350. @import "uview-ui/index.scss";
  351. </style>