socket.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  1. const {
  2. io
  3. } = require('./socket.io-v4.msgpack.js');
  4. var user = require('./services/user.js');
  5. const api = require('/config/api.js');
  6. const util = require('/utils/util.js');
  7. const UNLOGIN = 'NO_LOGIN'
  8. const btoa = require('./utils/btoa');
  9. const manyCount = 50
  10. import remote from './config.js'
  11. var app = getApp();
  12. var isIos = false
  13. wx.getSystemInfo({
  14. success: function (res) {
  15. isIos = res.platform == "ios"
  16. }
  17. })
  18. const debounce = (fn, wait) => {
  19. let callback = fn;
  20. let timerId = null;
  21. function debounced() {
  22. let context = this;
  23. let args = arguments;
  24. clearTimeout(timerId);
  25. timerId = setTimeout(function () {
  26. callback.apply(context, args);
  27. }, wait);
  28. }
  29. return debounced;
  30. }
  31. let urlToJson = (url = window.location.href) => { // 箭头函数默认传值为当前页面url
  32. let obj = {},
  33. index = url.indexOf('?'), // 看url有没有参数
  34. params = url.substr(index + 1); // 截取url参数部分 id = 1 & type = 2
  35. if (index != -1) { // 有参数时
  36. let parr = params.split('&'); // 将参数分割成数组 ["id = 1 ", " type = 2"]
  37. for (let i of parr) { // 遍历数组
  38. let arr = i.split('='); // 1) i id = 1 arr = [id, 1] 2)i type = 2 arr = [type, 2]
  39. obj[arr[0]] = arr[1]; // obj[arr[0]] = id, obj.id = 1 obj[arr[0]] = type, obj.type = 2
  40. }
  41. }
  42. return obj;
  43. }
  44. export default {
  45. joinUrl() {
  46. // 去除test-shop,转回shop
  47. // const url = true ? this.data.url.replace('shop.html', 'test-shop.html') : this.data.url;
  48. const url = this.data.url;
  49. let options = {
  50. API_BASE_URL: api.API_BASE_URL,
  51. "url": url,
  52. // "url": 'http://192.168.0.112:8080',
  53. "reload": this.data.reload,
  54. "token": wx.getStorageSync('token'),
  55. "code": this.mcode,
  56. "brandId": this.options.id,
  57. "open": this.data.showCommodity,
  58. "pauseVideo": this.pauseVideo,
  59. "bottom": this.data.bottom || 0,
  60. socket: {
  61. socketHost: remote.socketHost,
  62. path: '/new-zfb',
  63. options: {
  64. ...this.data.socketOptions,
  65. // nickname: encodeURI(encodeURI(this.data.socketOptions.nickname))
  66. nickname: encodeURIComponent(encodeURIComponent(this.data.socketOptions.nickname))
  67. }
  68. }
  69. }
  70. // let base = 'http://127.0.0.1:5500/index.html'
  71. // let base = remote.viewHost + '/shop-container/shop.html'
  72. let sponsor = !!this.data.canShow
  73. if (this.data.join && !this.options.join) {
  74. sponsor = false
  75. }
  76. // 33是从我的房间出来的
  77. if (Number(this.data.type) === 33) {
  78. sponsor = true;
  79. }
  80. // debugger
  81. // remote.viewHost
  82. let hostUrl
  83. if (options.url.indexOf('www.4dkankan.com') != -1) {
  84. hostUrl = 'https://www.4dkankan.com/shop-container-zfb/'
  85. } else if (options.url.indexOf('test.4dkankan.com') != -1) {
  86. hostUrl = 'https://test.4dkankan.com/shop-container-zfb/'
  87. } else {
  88. // hostUrl = 'https://zfb.4dkankan.com/shop-container/'
  89. // hostUrl = remote.viewHost + '/shop-container/'
  90. hostUrl = remote.viewHost + '/shop-container-v4/'
  91. }
  92. // let base = remote.viewHost + '/shop-container/fashilong.html?env=' + remote.env + '&sponsor=' + sponsor + '&many=' + this.data.many
  93. let base = hostUrl + 'fashilong.html?time=' + Date.now() + '&env=' + remote.env + '&sponsor=' + sponsor + '&many=' + this.data.many
  94. // let base = remote.viewHost + '/shop.html'
  95. this.data.reload = false
  96. this.data.showCommodity = false
  97. //上线前隐藏Vlog
  98. // options.url = options.url + '&vlog';
  99. if (!this.data.webviewUrl) {
  100. console.log(base)
  101. this.setData({
  102. 'webviewUrl': base + '#' + JSON.stringify(options)
  103. })
  104. } else {
  105. this.socketSendMessage('clientSyncAction', {
  106. sender: 'h5',
  107. type: 'hashChange',
  108. data: options
  109. })
  110. }
  111. },
  112. onShow() {
  113. this.setData({
  114. isIos,
  115. showComtypesAllTab: false
  116. })
  117. // wx.showToast({
  118. // title: '测试--socket.connected' + this.socket.connected,
  119. // })
  120. const onlineAction = () => {
  121. this.pauseVideo = false
  122. this.joinUrl()
  123. // debugger
  124. this.socketSendMessage('changeOnlineStatus', {
  125. status: 1
  126. })
  127. }
  128. console.warn("socketInstance-1", this.socketInstance);
  129. if (this.socketInstance) {
  130. if (!this.socketInstance.connected) {
  131. // wx.showToast({
  132. // title: 'socketInstance-2',
  133. // icon: 'none',
  134. // duration: 5000
  135. // })
  136. // this.socketInstance.connect();
  137. // wx.showModal({
  138. // title: '提示',
  139. // content: '欧克',
  140. // showCancel: false,
  141. // confirmColor: '#0075DC',
  142. // success: function (res) {}
  143. // })
  144. setTimeout(onlineAction, 300)
  145. } else {
  146. // wx.showToast({
  147. // title: 'socketInstance-3',
  148. // icon: 'none',
  149. // duration: 5000
  150. // })
  151. onlineAction();
  152. }
  153. }
  154. // if (this.socketSendMessage) {
  155. // this.pauseVideo = false
  156. // this.joinUrl()
  157. // // debugger
  158. // this.socketSendMessage('changeOnlineStatus', {
  159. // status: 1
  160. // })
  161. // }
  162. },
  163. changeShowComtypesAllTab(ev) {
  164. this.setData({
  165. showCommodity: false
  166. })
  167. setTimeout(() => {
  168. this.setData({
  169. showComtypesAllTab: ev.currentTarget.dataset.show,
  170. showCommodity: true
  171. })
  172. }, 100)
  173. },
  174. async authorizeRecord() {
  175. let isAuth = await new Promise((r, j) => {
  176. wx.authorize({
  177. scope: 'scope.record',
  178. success: () => r(true),
  179. fail: () => r(false)
  180. })
  181. })
  182. if (isAuth) return true
  183. let res = await new Promise(r => {
  184. wx.showModal({
  185. title: '提示',
  186. content: '您未授权录音,说话功能将无法使用',
  187. showCancel: true,
  188. confirmText: "授权",
  189. confirmColor: "#52a2d8",
  190. success: res => r(res),
  191. fail: () => r(false)
  192. })
  193. })
  194. if (!res || res.cancel) return;
  195. isAuth = await new Promise((r) => {
  196. wx.openSetting({
  197. success: res => r(res.authSetting['scope.record']),
  198. fail: () => r(false)
  199. })
  200. })
  201. return isAuth
  202. },
  203. // 获取录音权限状态
  204. async getAuthorizeRecordStatus() {
  205. const isAuth = await new Promise((r, j) => {
  206. wx.authorize({
  207. scope: 'scope.record',
  208. success: () => r(true),
  209. fail: () => r(false)
  210. })
  211. })
  212. return Promise.resolve(isAuth)
  213. },
  214. async agetUserInfo() {
  215. const res = await util.request(api.UserInfo)
  216. if (res.errno === 401) {
  217. return {
  218. userId: UNLOGIN,
  219. avatar: ''
  220. }
  221. } else {
  222. const data = res.data
  223. data.region = data.city ? data.city.split(',') : []
  224. data.birthday = data.birthday || '1990-01-01'
  225. return data
  226. }
  227. },
  228. async getUserInfo() {
  229. let userInfo = wx.getStorageSync('userInfo');
  230. let token = wx.getStorageSync('token');
  231. if (userInfo && userInfo.userId && token) {
  232. let info = await this.agetUserInfo()
  233. return {
  234. ...userInfo,
  235. ...info,
  236. avatarUrl: info.avatar
  237. };
  238. } else {
  239. return {
  240. userId: UNLOGIN,
  241. avatar: ''
  242. }
  243. }
  244. // let detail
  245. // let isAuth = await new Promise((r, j) => {
  246. // wx.authorize({
  247. // scope: 'scope.userInfo',
  248. // success: () => r(true),
  249. // fail: () => r(false)
  250. // })
  251. // })
  252. // if (!isAuth) {
  253. // this.setData({userAuth: true})
  254. // detail = await new Promise(r => {
  255. // this.bindGetUserInfo = (e) => {
  256. // if (e.detail.userInfo) {
  257. // this.setData({userAuth: false})
  258. // console.log('gei', e.detail)
  259. // r(e.detail)
  260. // }
  261. // }
  262. // })
  263. // } else {
  264. // detail = await new Promise(r => {
  265. // wx.getUserInfo({
  266. // success: res => r(res),
  267. // fail: () => r(false)
  268. // })
  269. // })
  270. // }
  271. // try {
  272. // let res = await user.loginByWeixin(detail)
  273. // app.globalData.userInfo = res.data.userInfo;
  274. // app.globalData.token = res.data.token;
  275. // return res.data.userInfo
  276. // } catch(e) {
  277. // return false
  278. // }
  279. },
  280. login() {
  281. getApp().setLoginProps(false)
  282. },
  283. async getSocketOptions(sceneId, roomId) {
  284. //TODO
  285. console.log('this.data.type', this.data.type)
  286. // debugger;
  287. let result
  288. if (Number(this.data.type) === 33) {
  289. result = await util.request(api.enterRoom, {
  290. businessId: roomId
  291. }, 'POST', 'application/json')
  292. if (result.code !== 200) {
  293. wx.showModal({
  294. content: result.error,
  295. complete: () => {
  296. if (result.message && result.message.isAnchor == 0) {
  297. wx.switchTab({
  298. url: '/pages/index/index',
  299. })
  300. } else {
  301. wx.redirectTo({
  302. url: '/pages/roomManger/roomManger',
  303. });
  304. }
  305. }
  306. })
  307. return
  308. }
  309. }
  310. const capacities = !!result ? result.message.capacities : 50 // 房间限制人数
  311. const {
  312. isAnchor,
  313. assistant,
  314. } = !!result ? result.message : {}
  315. let userInfo = await this.getUserInfo()
  316. // console.log('---', userInfo)
  317. // this.setData({
  318. // userInfoa: userInfo.nickname.split('').join(' ')
  319. // })
  320. userInfo.nickname = userInfo.nickname.replace(/[^\u4E00-\u9FA5A-Za-z0-9]/g, '')
  321. if (userInfo.nickname == "") {
  322. userInfo.nickname = "口"
  323. }
  324. // this.role !== 'leader'
  325. // let roomType
  326. // if ((!this.data.canShow && !this.data.join) || (this.data.join && !this.options.join)) {
  327. // // roomType = '1v1'
  328. // if (this.options.roomId) {
  329. // this.role = 'leader'
  330. // }
  331. // console.log('**************')
  332. // console.log(this.options)
  333. // }
  334. let isAllowMic // 真正MIC权, 房主与 授权一个 要在房间isAllowMic开启
  335. if (Number(isAnchor) === 1) {
  336. this.role = "leader"
  337. isAllowMic = 1
  338. } else {
  339. this.role = 'customer'
  340. isAllowMic = 0
  341. }
  342. // 助手改用isAssistant作为flag, role因为V3不能新增角色,只支持leader/customer。
  343. let isAssistant
  344. if (assistant && assistant.userId && assistant.userId == userInfo.userId) {
  345. isAssistant = true;
  346. } else {
  347. isAssistant = false
  348. }
  349. console.log('进入房间角色, 是否助手 %s', this.role, isAssistant);
  350. const isAuthMic = await this.getAuthorizeRecordStatus();
  351. // console.log('当前用户录音权限状态', isAuthMic)
  352. this.setData({
  353. isAllowMic,
  354. isAuthMic
  355. })
  356. const assistantId = (assistant && assistant.userId) ? assistant.userId : '';
  357. if (capacities) {
  358. this.setData({
  359. peopleCount: capacities
  360. })
  361. } else {
  362. this.setData({
  363. peopleCount: manyCount
  364. })
  365. }
  366. return {
  367. role: this.role,
  368. userId: userInfo.userId,
  369. // roomType,
  370. avatar: userInfo.avatarUrl,
  371. nickname: userInfo.nickname,
  372. voiceStatus: getApp().globalData.voiceProps.noMute ? 0 : 2,
  373. isAuthMic: isAuthMic ? 1 : 0,
  374. isAllowMic: isAllowMic,
  375. roomId: roomId,
  376. sceneNumber: sceneId,
  377. onlineStatus: 1,
  378. assistantId: assistantId,
  379. isAssistant: isAssistant ? 1 : 0,
  380. oid: userInfo.weixin_openid,
  381. userLimitNum: capacities || 50
  382. }
  383. },
  384. async socketStart({
  385. sceneId,
  386. roomId,
  387. options
  388. }) {
  389. if (!options) {
  390. options = await this.getSocketOptions(sceneId, roomId)
  391. }
  392. console.log('小程序参数', options)
  393. if (!options.roomId) {
  394. return Promise.resolve(false)
  395. }
  396. // 真正进入统计
  397. util.request(api.trackRoom, {
  398. roomId: options.roomId,
  399. type: 0
  400. }, 'POST', 'application/json')
  401. let userInfo = await this.getUserInfo()
  402. let socket = io(remote.socketHost, {
  403. path: '/new-zfb',
  404. transport: ['websocket'],
  405. extraHeaders: {
  406. "oid": userInfo.weixin_openid
  407. },
  408. query: {
  409. ...options,
  410. isClient: true,
  411. from: 2
  412. }
  413. });
  414. this.socketInstance = socket
  415. console.error('新建socket Room', options.roomId)
  416. this.setData({
  417. socketStatus: 0,
  418. })
  419. socket.on('connect', () => this.setData({
  420. socketStatus: 1
  421. }))
  422. socket.on('connect_error', () => this.setData({
  423. socketStatus: -1
  424. }))
  425. socket.on('connect_timeout', () => this.setData({
  426. socketStatus: -1
  427. }))
  428. socket.on('disconnect', () => this.setData({
  429. socketStatus: -1
  430. }))
  431. socket.on('reconnect', () => {
  432. // wx.showToast({
  433. // title: '重连',
  434. // })
  435. this.setData({
  436. socketStatus: this.data.socketStatus
  437. })
  438. let noMute = getApp().globalData.voiceProps.noMute
  439. this.socketSendMessage('changeVoiceStatus', {
  440. status: noMute ? 0 : 2
  441. })
  442. this.socketSendMessage('changeOnlineStatus', {
  443. status: 1
  444. })
  445. })
  446. socket.on('reconnect_failed', () => this.setData({
  447. socketStatus: -1
  448. }))
  449. socket.on('error', () => this.setData({
  450. socketStatus: -1
  451. }))
  452. socket.on('roomIn', config => {
  453. let enableTalk = config.roomsConfig.enableTalk !== false
  454. let noMute = getApp().globalData.voiceProps.noMute
  455. getApp().globalData.voiceProps.force = enableTalk
  456. if (!enableTalk && !noMute) {
  457. if (this.role !== 'leader') {
  458. // this.mic()
  459. }
  460. }
  461. })
  462. this.socketSendMessage = (event, obj) => {
  463. console.error('发送 socket Room', options.roomId, event, obj)
  464. socket.emit(event, obj)
  465. }
  466. socket.on('clientSyncAction', (data) => {
  467. console.log('调用', data.type, '方法', data)
  468. if (this[data.type]) {
  469. this[data.type](data)
  470. } else if (data.type == 'wx-subscribe') {
  471. this.getUrlCode(data.data)
  472. } else {
  473. console.error('没有', data.type, '方法')
  474. }
  475. })
  476. socket.on('action', (data) => {
  477. if (data.type === 'navigateToGoods') {
  478. this.navigateToGoodsAction(data.data)
  479. }
  480. })
  481. socket.on('changeRoomEnableTalk', config => {
  482. if (this.role !== 'leader') {
  483. this.changeRoomEnableTalk(config)
  484. }
  485. })
  486. socket.on('startCall', this.startCall.bind(this))
  487. socket.on('stopCall', (data) => {
  488. console.log('on stopCall')
  489. this.stopCall(data)
  490. })
  491. this.handleSomeOneInRoom = this.handleSomeOneInRoom.bind(this)
  492. // socket.on('someOneInRoom', debounce(this.handleSomeOneInRoom, 100))
  493. socket.on('someOneInRoom', debounce(this.handleSomeOneInRoom, 100))
  494. socket.on('someOneLeaveRoom', (user, data) => {
  495. this.handleSomeOneLeave(user)
  496. })
  497. socket.on('roomClose', (data) => {
  498. console.log('on roomClose')
  499. this.stopCall(data)
  500. })
  501. socket.on('autoReJoin', (data) => {
  502. console.log('on autoReJoin')
  503. if ('roomId' in data) {
  504. options.roomId = Number(data.roomId)
  505. }
  506. })
  507. // 有MIC通知,主要是其他用户禁MIC 移到中间层处理。
  508. // socket.on('beHasMic', (data) => {
  509. // const socketOptions = this.data.socketOptions
  510. // if (data.user) {
  511. // const isOther = (socketOptions.role !== 'leader' && (Number(socketOptions.userId) !== Number(data.user.userId)));
  512. // if (isOther) {
  513. // this.closeMic();
  514. // // wx.showToast({
  515. // // title: '关mic' + isOther
  516. // // })
  517. // }
  518. // }
  519. // })
  520. socket.on("beKicked", data => {
  521. const that = this
  522. if (data.userId && data.roomId) {
  523. const socketOptions = this.data.socketOptions
  524. const userId = data.userId
  525. const roomId = data.roomId
  526. // debugger
  527. if (socketOptions.userId == userId && this.options.roomId == roomId) {
  528. wx.showToast({
  529. title: '您已被踢出房间!',
  530. icon: 'none',
  531. complete: () => {}
  532. })
  533. setTimeout(() => {
  534. that.socketStop();
  535. wx.switchTab({
  536. url: '/pages/index/index',
  537. })
  538. }, 1000)
  539. }
  540. }
  541. });
  542. socket.on("roomMaximum", () => {
  543. this.setData({
  544. roomMaximum: true
  545. })
  546. });
  547. //全员退出
  548. socket.on('roomDisMiss', () => {
  549. // wx.showToast({
  550. // title: '全员退出',
  551. // });
  552. this.setData({
  553. roomDisMiss: true
  554. })
  555. // this.exitRoom();
  556. })
  557. //服务器未知错误重进
  558. socket.on('unKnowError', () => {
  559. this.setData({
  560. unKnowError: true
  561. })
  562. })
  563. //被动通知开关MIC 要3秒后
  564. socket.on('serverOnMic', ({
  565. voiceStatus
  566. }) => {
  567. setTimeout(() => {
  568. if (Number(voiceStatus) === 2) {
  569. // wx.showToast({
  570. // title: '开MIC',
  571. // icon:'none'
  572. // })
  573. this.openMic();
  574. }
  575. if (Number(voiceStatus) === 0) {
  576. // wx.showToast({
  577. // title: '关MIC',
  578. // icon:'none'
  579. // })
  580. this.closeMic();
  581. }
  582. }, 3000)
  583. });
  584. this.socketStop = () => {
  585. if (socket) {
  586. socket.close()
  587. console.error('断开 并滞空 socket Room', options.roomId)
  588. this.setData({
  589. socketStatus: 2
  590. })
  591. socket = null
  592. }
  593. }
  594. return options
  595. },
  596. getUrlCode(url) {
  597. this.socketSendMessage('clientSyncAction', {
  598. sender: 'wx',
  599. type: 'wx-subscribe-result',
  600. data: 3020
  601. })
  602. // wx.request({
  603. // url: url, //仅为示例,并非真实的接口地址
  604. // method: 'get',
  605. // success: (res) => {
  606. // let code = -1
  607. // if (typeof res.data.code != 'undefined') {
  608. // code = res.data.code
  609. // }
  610. // this.socketSendMessage('clientSyncAction', {
  611. // sender: 'wx',
  612. // type: 'wx-subscribe-result',
  613. // data: code
  614. // })
  615. // },
  616. // fail: (err) => {
  617. // console.log(err)
  618. // }
  619. // })
  620. },
  621. changeRoomEnableTalk(data) {
  622. console.log(data)
  623. let noMute = getApp().globalData.voiceProps.noMute
  624. getApp().globalData.voiceProps.force = data.enableTalk
  625. // noMute true 静音
  626. // enableTalk false 静音
  627. if (!!data.enableTalk === !!noMute) {
  628. this.mic()
  629. }
  630. },
  631. navigateToGoods({
  632. data
  633. }) {
  634. // wx.showToast({
  635. // title: JSON.stringify(data).substr(40)
  636. // })
  637. this.navigateToGoodsAction(data)
  638. },
  639. navigateToGoodsAction(id) {
  640. wx.navigateTo({
  641. url: '/pages/goods/goods?id=' + id,
  642. })
  643. },
  644. getUrl(url, socketOptions, isJoin) {
  645. url += '&room_id=' + socketOptions.roomId + '&user_id=' + socketOptions.userId + '&origin=fashilong'
  646. if (isJoin) {
  647. url += '&role=' + this.role + '&shopping'
  648. } else {
  649. url += '&role=' + this.role
  650. }
  651. console.error(url)
  652. console.log(isJoin)
  653. return url
  654. },
  655. navigateToMiniProgram(data) {
  656. wx.showModal({
  657. title: '温馨提示',
  658. content: '即将跳到其他小程序,是否继续?',
  659. showCancel: true, //是否显示取消按钮
  660. cancelText: "取消", //默认是“取消”
  661. confirmText: "确定", //默认是“确定”
  662. success: function (res) {
  663. if (res.cancel) {
  664. //点击取消,wx.navigateBack
  665. } else {
  666. wx.navigateToMiniProgram(data.data)
  667. }
  668. },
  669. fail: function (res) {
  670. //接口调用失败的回调函数,wx.navigateBack
  671. },
  672. complete: function (res) {
  673. //接口调用结束的回调函数(调用成功、失败都会执行)
  674. },
  675. })
  676. },
  677. async handleSomeOneInRoom(data) {
  678. if (data && data.user) {
  679. console.log('handleSomeOneInRoom', data)
  680. this.startCall(data)
  681. }
  682. },
  683. async startCall(data) {
  684. //TODO 触发三次
  685. console.log('startCall-data', data)
  686. // if( this.role =='leader'){
  687. this.setData({
  688. shareStatus: 1
  689. })
  690. if (!data) return;
  691. this.setData({
  692. surplus: this.data.peopleCount - data.roomsPerson.length
  693. })
  694. //undefined是未授权,状态为3
  695. let voiceStatus
  696. if (!this.isAuthorizeRecord) {
  697. const unAuth = await this.authorizeRecord();
  698. if (typeof unAuth === 'undefined') {
  699. // debugger
  700. voiceStatus = 3
  701. } else {
  702. voiceStatus = Number(unAuth)
  703. }
  704. }
  705. //限制只有主持人才可以开麦
  706. // if (this.role == 'leader') {
  707. // if (!this.isAuthorizeRecord) {
  708. // const voiceStatus = Number(await this.authorizeRecord())
  709. // this.isAuthorizeRecord = true
  710. // // getApp().setVoiceProps({
  711. // // noMute: !voiceStatus
  712. // // })
  713. // // console.log(getApp().globalData.voiceProps.noMute)
  714. // // this.socketSendMessage('changeVoiceStatus', {
  715. // // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  716. // // })
  717. // // this.data.socketOptions.voiceStatus = 1
  718. // // this.socketSendMessage('changeVoiceStatus', {status: noMute ? 0 : 2})
  719. // }
  720. // }
  721. const socketOptions = this.data.socketOptions
  722. getApp().globalData.roomId = socketOptions.roomId
  723. const user = data.roomsPerson.find(user => user.userId == socketOptions.userId)
  724. if (!user) {
  725. return
  726. }
  727. //屏蔽有人进来才开麦克风
  728. // if (data.roomsPerson.length <= 1) {
  729. // return
  730. // }
  731. user.noMute = getApp().globalData.voiceProps.noMute
  732. getApp().setVoiceProps({
  733. ...user,
  734. action: 'startCall'
  735. })
  736. // this.socketSendMessage('changeVoiceStatus', {
  737. // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  738. // })
  739. // }
  740. },
  741. stopCall() {
  742. console.error('stopCall')
  743. this.setData({
  744. shareStatus: 0
  745. })
  746. getApp().setVoiceProps({
  747. noMute: false,
  748. action: 'stopCall'
  749. })
  750. if (this.runManager) {
  751. // this.recorderManager.stop()
  752. this.runManager = false
  753. }
  754. },
  755. handleSomeOneLeave(data) {
  756. if (data.roomsPerson.length <= 1) {
  757. // this.stopCall()
  758. }
  759. this.setData({
  760. surplus: this.data.peopleCount - data.roomsPerson.length
  761. })
  762. },
  763. //deprecated
  764. async newRoomBk(data) {
  765. if (data.roomId) return;
  766. this.stopCall()
  767. getApp().globalData.rtcParams = []
  768. getApp().globalData.pusher = ''
  769. if (this.data.join && !this.options.join) {
  770. wx.switchTab({
  771. url: '/pages/index/index',
  772. })
  773. return;
  774. }
  775. this.role = this.data.canShow ? 'leader' : 'customer'
  776. let options = await this.getSocketOptions(this.mcode)
  777. this.socketSendMessage('clientSyncAction', {
  778. type: 'newRoom',
  779. data: options
  780. })
  781. setTimeout(async () => {
  782. this.wssSuccess = false
  783. this.socketStop && this.socketStop()
  784. this.data.many = !!this.data.canShow
  785. // this.setData({
  786. // // peopleCount: this.data.many ? manyCount : 5
  787. // peopleCount: manyCount
  788. // })
  789. let base = this.base
  790. let socketOptions = await this.socketStart({
  791. options
  792. })
  793. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  794. this.base = base
  795. this.setData({
  796. url,
  797. socketOptions,
  798. })
  799. this.joinUrl()
  800. this.setData({
  801. socketOptions
  802. })
  803. this.loadConponSuccess = true
  804. this.readySendCouponCtrl()
  805. }, 300)
  806. },
  807. // 真正退出房间
  808. async exitRoom() {
  809. const roomId = this.data.socketOptions.roomId;
  810. const role = this.role;
  811. const result = await util.request(api.exitRoom, {
  812. businessId: roomId
  813. }, 'POST', 'application/json');
  814. this.socketSendMessage('stopCall', {
  815. from: 2
  816. })
  817. this.stopCall();
  818. this.socketStop();
  819. if (role === 'leader') {
  820. wx.redirectTo({
  821. url: '/pages/roomManger/roomManger',
  822. });
  823. } else {
  824. wx.switchTab({
  825. url: '/pages/index/index'
  826. });
  827. }
  828. },
  829. async exit() {
  830. // this.stopCall()
  831. getApp().globalData.rtcParams = []
  832. getApp().globalData.pusher = ''
  833. this.socketStop && this.socketStop()
  834. this.role = 'leader'
  835. let base = this.base
  836. let socketOptions = await this.socketStart({
  837. sceneId: this.mcode
  838. })
  839. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  840. this.base = base
  841. wx.nextTick(() => {
  842. setTimeout(() => {
  843. this.setData({
  844. url,
  845. loadUrl: true,
  846. socketOptions,
  847. showCommodityCtrl: false,
  848. hideWebView: false,
  849. reload: true
  850. })
  851. this.joinUrl()
  852. }, 500)
  853. })
  854. },
  855. clearDebuger() {
  856. this.setData({
  857. debugerInfo: ''
  858. })
  859. },
  860. async mic({
  861. data
  862. }) {
  863. if (Number(data.user.isAllowMic) === 1) {
  864. let noMute = getApp().globalData.voiceProps.noMute
  865. // debugger
  866. // noMute true 静音
  867. // enableTalk false 静音
  868. // if (!!getApp().globalData.voiceProps.force === !!noMute)
  869. // return
  870. // if (!getApp().globalData.voiceProps.force && (!this.data.socketOptions.voiceStatus || noMute)) return;
  871. if (!this.data.socketOptions.voiceStatus) {
  872. let voiceStatus = await this.authorizeRecord()
  873. if (voiceStatus) {
  874. this.data.socketOptions.voiceStatus = 1
  875. noMute = false
  876. } else {
  877. noMute = true
  878. }
  879. } else {
  880. noMute = !noMute
  881. }
  882. getApp().globalData.voiceProps.noMute = noMute
  883. this.socketSendMessage('changeVoiceStatus', {
  884. status: noMute ? 0 : 2,
  885. user: data.user
  886. })
  887. getApp().setVoiceProps({
  888. noMute
  889. })
  890. wx.showToast({
  891. title: `已${noMute ? '关闭' : '开启'}麦克风`,
  892. })
  893. }
  894. },
  895. closeMic() {
  896. getApp().globalData.voiceProps.noMute = true
  897. this.socketSendMessage('changeVoiceStatus', {
  898. status: 0,
  899. })
  900. getApp().setVoiceProps({
  901. noMute: true
  902. })
  903. },
  904. openMic() {
  905. getApp().globalData.voiceProps.noMute = false
  906. this.socketSendMessage('changeVoiceStatus', {
  907. status: 2,
  908. })
  909. getApp().setVoiceProps({
  910. noMute: false
  911. })
  912. },
  913. callPhone() {
  914. wx.makePhoneCall({
  915. phoneNumber: this.data.contractPhone,
  916. })
  917. this.setData({
  918. showContact: false
  919. })
  920. },
  921. /**
  922. * 用户点击右上角分享
  923. */
  924. onShareAppMessage: function (res) {
  925. let {
  926. id,
  927. newPicUrl
  928. } = this.data
  929. if (res.from === 'button') {
  930. this.setData({
  931. sendShare: false
  932. })
  933. return {
  934. title: '【好友推荐】一起来云逛吧',
  935. imageUrl: newPicUrl,
  936. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=true&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`,
  937. }
  938. } else {
  939. return {
  940. imageUrl: newPicUrl,
  941. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=false`,
  942. }
  943. }
  944. },
  945. /**
  946. * 生命周期函数--监听页面卸载
  947. */
  948. onUnload: function () {
  949. console.log('on onUnload')
  950. // this.socketSendMessage('stopCall', {})
  951. // this.stopCall()
  952. this.socketStop && this.socketStop()
  953. getApp().globalData.pusher = ''
  954. },
  955. cart(data) {
  956. this.setData({
  957. showCommodityCtrl: data.data
  958. })
  959. },
  960. share() {
  961. console.log('share-debug')
  962. const companyName = `指房宝(杭州)科技有限公司`
  963. const vrLink = `/pages/webview/index`
  964. const img_url = this.data.newPicUrl || 'http://video.cgaii.com/new4dage/images/images/home_2_a.jpg'
  965. const shareImg = img_url
  966. this.count = this.count || 0
  967. console.log('share-debug many:%s shareStatus: %s', !!this.data.many, this.data.shareStatus);
  968. if (this.data.many && this.data.shareStatus == 1) {
  969. //开启一起逛时候的分享
  970. console.log(`share-debug: /pages/shareRoom/shareRoom?img_url=${btoa(img_url)}&vrLink=${btoa(vrLink)}&id=${this.data.id}&type=${this.data.type}&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`)
  971. console.log('share-debug', this.data.socketOptions)
  972. wx.navigateTo({
  973. url: `/pages/shareRoom/shareRoom?img_url=${btoa(img_url)}&vrLink=${btoa(vrLink)}&id=${this.data.id}&type=${this.data.type}&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`,
  974. })
  975. } else {
  976. console.log(`share-debug: /pages/shared/shared?img_url=${btoa(img_url)}&shareImg=${btoa(shareImg)}&companyName=${companyName}&vrLink=${btoa(vrLink)}&id=${this.data.id}&type=${this.data.type}`);
  977. wx.navigateTo({
  978. url: `/pages/shared/shared?img_url=${btoa(img_url)}&shareImg=${btoa(shareImg)}&companyName=${companyName}&vrLink=${btoa(vrLink)}&id=${this.data.id}&type=${this.data.type}`,
  979. })
  980. }
  981. },
  982. back(data) {
  983. if (data.sender !== 'h5') return;
  984. wx.switchTab({
  985. url: '/pages/index/index'
  986. })
  987. this.setData({
  988. showCommodityCtrl: false
  989. })
  990. },
  991. service() {
  992. this.setData({
  993. showContact: true,
  994. showCommodity: false,
  995. showCoupon: false
  996. })
  997. },
  998. invite(data) {
  999. if (data.sender !== 'h5') return;
  1000. // 分享房间进入统计
  1001. if (this.data.socketOptions.roomId !== '888888') {
  1002. util.request(api.trackRoom, {
  1003. roomId: this.data.socketOptions.roomId,
  1004. type: 1,
  1005. }, 'POST', 'application/json')
  1006. }
  1007. this.setData({
  1008. sendShare: true,
  1009. count: ++this.data.count
  1010. })
  1011. },
  1012. coupon(data) {
  1013. if (data.sender !== 'h5') return;
  1014. this.setData({
  1015. showContact: false,
  1016. showCommodity: false,
  1017. showCoupon: true
  1018. })
  1019. },
  1020. liveGotoGood(ev) {
  1021. let id = ev.currentTarget.dataset.item.goodsId
  1022. wx.navigateTo({
  1023. url: '/pages/goods/goods?id=' + id,
  1024. })
  1025. },
  1026. gotoGoodsDOM(event) {
  1027. this.gotoGoods(event.currentTarget.dataset.item.hotIdList[0])
  1028. },
  1029. gotoGoodsSocket(data) {
  1030. this.gotoGoods(data.data)
  1031. },
  1032. gotoGoods(id) {
  1033. console.log('---', id)
  1034. this.socketSendMessage('clientSyncAction', {
  1035. type: 'openTag',
  1036. data: id
  1037. })
  1038. this.setData({
  1039. showCommodity: false
  1040. })
  1041. this.joinUrl()
  1042. },
  1043. addCard(event) {
  1044. wx.navigateTo({
  1045. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=addCard',
  1046. })
  1047. },
  1048. buyGoods(event) {
  1049. wx.navigateTo({
  1050. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=buyGoods',
  1051. })
  1052. },
  1053. showCommodityFn() {
  1054. this.setData({
  1055. showCommodity: true,
  1056. showContact: false,
  1057. showCoupon: false
  1058. })
  1059. this.joinUrl()
  1060. },
  1061. hideComodity() {
  1062. this.setData({
  1063. showCommodity: false
  1064. })
  1065. this.joinUrl()
  1066. },
  1067. hideCoupon() {
  1068. this.setData({
  1069. showCoupon: !this.data.showCoupon
  1070. })
  1071. },
  1072. async receive(ev) {
  1073. let item = ev.target.dataset.item
  1074. try {
  1075. // wx.showToast({
  1076. // title: '领取优惠卷',
  1077. // })
  1078. // return;
  1079. if (item.hasReceived || item.number <= item.receiveNumber) return;
  1080. let res = await util.request(api.CouponExchange, {
  1081. couponId: item.id
  1082. })
  1083. if (res.code === 0) {
  1084. wx.showToast({
  1085. title: '已成功领取',
  1086. success: () => {
  1087. this.setData({
  1088. showCoupon: false
  1089. })
  1090. wx.nextTick(() => {
  1091. this.setData({
  1092. coupons: this.data.coupons.map(citem => {
  1093. return {
  1094. ...citem,
  1095. hasReceived: citem.id === item.id ? true : citem.hasReceived
  1096. }
  1097. }),
  1098. showCoupon: true
  1099. })
  1100. })
  1101. }
  1102. })
  1103. } else if (res.errno === 401) {
  1104. getApp().setLoginProps(false)
  1105. } else {
  1106. wx.showToast({
  1107. title: res.msg,
  1108. })
  1109. }
  1110. } catch (e) {
  1111. console.error(e)
  1112. wx.showToast({
  1113. icon: 'none',
  1114. title: '领取失败',
  1115. })
  1116. }
  1117. },
  1118. async getCouponList(id) {
  1119. const success = (res) => {
  1120. this.setData({
  1121. coupons: res.data.list.map(item => {
  1122. item.typeMoney = item.typeMoney.toString()
  1123. item.fontSize = item.typeMoney.length === 3 ? '90rpx' :
  1124. item.typeMoney.length === 4 ? '70rpx' : '130rpx'
  1125. return item
  1126. })
  1127. })
  1128. this.loadConponSuccess = true
  1129. this.readySendCouponCtrl()
  1130. }
  1131. let res = await util.request(api.BrandCouponList, {
  1132. brandId: id,
  1133. pageNum: 1,
  1134. pageSize: 10000
  1135. }, 'GET')
  1136. console.log(res)
  1137. if (res.code === 0) {
  1138. success(res)
  1139. } else {
  1140. let res = await util.request(api.UNBrandCouponList, {
  1141. brandId: id,
  1142. pageNum: 1,
  1143. pageSize: 10000
  1144. }, 'GET')
  1145. success(res)
  1146. }
  1147. },
  1148. ready() {
  1149. this.wssSuccess = true
  1150. this.readySendCouponCtrl()
  1151. },
  1152. readySendCouponCtrl() {
  1153. if (this.wssSuccess && this.loadConponSuccess) {
  1154. this.loadConponSuccess = false
  1155. this.socketSendMessage('clientSyncAction', {
  1156. type: 'showCoupon',
  1157. data: this.data.coupons.length > 0
  1158. })
  1159. }
  1160. },
  1161. getBrand: function (id, code) {
  1162. this.getGoodsCount(code, id)
  1163. return;
  1164. },
  1165. getGoodsCount(code, id) {
  1166. util.request(api.GoodsNumCount, {
  1167. isDelete: 0,
  1168. isOnSale: 1,
  1169. brandId: id
  1170. }, 'GET')
  1171. .then(res => {
  1172. if (res.errno === 0) {
  1173. this.setData({
  1174. goodsCount: res.data
  1175. })
  1176. }
  1177. this.getCouponList(id)
  1178. })
  1179. },
  1180. getGoodsList(id, category_id) {
  1181. var that = this;
  1182. if (!(this.data.navList && this.data.navList.length)) {
  1183. that.navDatas = {}
  1184. let navDatas = this.data.navList = this.data.comtypes
  1185. // util.request(api.GoodsCategory, { id: category_id })
  1186. // .then(function (res) {
  1187. // if (res.errno == 0) {
  1188. // let navDatas = res.data.brotherCategory
  1189. // that.setData({
  1190. // navList: navDatas,
  1191. // currTypeId: category_id
  1192. // });
  1193. that.navDatas = {}
  1194. navDatas.forEach(item => {
  1195. util.request(api.GoodsList, {
  1196. brandId: id,
  1197. categoryId: item.category_id,
  1198. page: that.data.page,
  1199. size: that.data.size
  1200. })
  1201. .then(res => {
  1202. if (res.errno === 0) {
  1203. that.navDatas[item.category_id] = res.data.goodsList
  1204. }
  1205. })
  1206. })
  1207. // }
  1208. // })
  1209. }
  1210. if (that.navDatas[category_id]) {
  1211. if (!isIos) {
  1212. let showCommodity = that.data.showCommodity
  1213. that.setData({
  1214. showCommodity: false
  1215. })
  1216. setTimeout(() => {
  1217. wx.nextTick(() => {
  1218. that.setData({
  1219. goodsList: that.navDatas[category_id],
  1220. currTypeId: category_id,
  1221. showCommodity: showCommodity
  1222. });
  1223. })
  1224. }, 500)
  1225. } else {
  1226. that.setData({
  1227. goodsList: that.navDatas[category_id],
  1228. currTypeId: category_id,
  1229. });
  1230. }
  1231. } else {
  1232. console.error('诱惑去啦')
  1233. util.request(api.GoodsList, {
  1234. brandId: id,
  1235. categoryId: category_id,
  1236. page: that.data.page,
  1237. size: that.data.size
  1238. })
  1239. .then(function (res) {
  1240. if (res.errno === 0) {
  1241. that.setData({
  1242. goodsList: res.data.goodsList,
  1243. currTypeId: category_id
  1244. });
  1245. // this.data.navList
  1246. }
  1247. });
  1248. }
  1249. },
  1250. getBrandDetail: function (id, type, cb) {
  1251. console.log('getBrandDetail-params', id, type)
  1252. util.request(api.BrandDetail, {
  1253. id: id,
  1254. type: type,
  1255. }).then((res) => {
  1256. console.log('getBrandDetail', res)
  1257. let base = res.data.brand.sceneUrl
  1258. // let base = 'http://192.168.0.112:8080/shop.html?m=t-7Uqj9Fq&origin=fashilong'
  1259. if (res.errno === 0) {
  1260. let url = base + "&sid=" + id
  1261. // debugger
  1262. this.setData({
  1263. id: id,
  1264. newPicUrl: res.data.brand.appListPicUrl,
  1265. sceneNum: res.data.brand.sceneNum,
  1266. canShow: res.data.brand.canShow,
  1267. contractPhone: res.data.brand.contractPhone,
  1268. contactInfo: {
  1269. contactPhone: res.data.brand.contactPhone || '',
  1270. contactHead: res.data.brand.contactHead || '',
  1271. contactCompanyName: res.data.brand.contactCompanyName || '',
  1272. contactNickName: res.data.brand.contactNickName || '',
  1273. brands: res.data.brand.brands || []
  1274. }
  1275. })
  1276. if (this.data.many === void 0) {
  1277. this.data.many = !!res.data.brand.canShow
  1278. }
  1279. this.setData({
  1280. // peopleCount: this.data.many ? manyCount : 5,
  1281. peopleCount: manyCount
  1282. })
  1283. if (!res.data.brand.canShow) {
  1284. this.role = 'customer'
  1285. } else if (!this.options.join) {
  1286. this.role = 'leader'
  1287. }
  1288. cb(url, urlToJson(url).m, )
  1289. }
  1290. });
  1291. },
  1292. sendContactInfo() {
  1293. this.socketSendMessage('getContactInfo', {
  1294. contactInfo: this.data.contactInfo,
  1295. })
  1296. },
  1297. selectType(ev) {
  1298. this.getGoodsList(this.options.id, ev.target.dataset.item.category_id)
  1299. },
  1300. hideCS() {
  1301. this.setData({
  1302. showCommodity: false,
  1303. showCoupon: false,
  1304. showContact: false
  1305. })
  1306. },
  1307. hideContact() {
  1308. this.setData({
  1309. showContact: false
  1310. })
  1311. },
  1312. calcShare() {
  1313. // this.exit()
  1314. this.setData({
  1315. sendShare: false
  1316. })
  1317. },
  1318. contactKf() {
  1319. let keys = Object.keys(this.navDatas)
  1320. let goodsId = this.navDatas[keys[0]][0].id
  1321. let user = wx.getStorageSync('userinfoDetail')
  1322. util.request(api.AddTalkCount, {
  1323. goodsId,
  1324. viewId: user && user.userId || '',
  1325. sceneNum: this.data.sceneNum
  1326. }, 'get')
  1327. this.hideAlert && this.hideAlert()
  1328. this.hideContact && this.hideContact()
  1329. },
  1330. onHide() {
  1331. this.socketSendMessage('changeOnlineStatus', {
  1332. status: 0
  1333. })
  1334. this.pauseVideo = true
  1335. this.joinUrl()
  1336. }
  1337. }