socket.js 34 KB

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