socket.js 35 KB

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