socket.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  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. if (result.message && result.message.isAnchor == 0) {
  259. wx.switchTab({
  260. url: '/pages/index/index',
  261. })
  262. } else {
  263. wx.redirectTo({
  264. url: '/pages/roomManger/roomManger',
  265. });
  266. }
  267. }
  268. })
  269. return
  270. }
  271. }
  272. const capacities = !!result ? result.message.capacities : 50 // 房间限制人数
  273. const {
  274. isAnchor,
  275. assistant,
  276. } = !!result ? result.message : {}
  277. let userInfo = await this.getUserInfo()
  278. // console.log('---', userInfo)
  279. // this.setData({
  280. // userInfoa: userInfo.nickname.split('').join(' ')
  281. // })
  282. userInfo.nickname = userInfo.nickname.replace(/[^\u4E00-\u9FA5A-Za-z0-9]/g, '')
  283. if (userInfo.nickname == "") {
  284. userInfo.nickname = "口"
  285. }
  286. // this.role !== 'leader'
  287. // let roomType
  288. // if ((!this.data.canShow && !this.data.join) || (this.data.join && !this.options.join)) {
  289. // // roomType = '1v1'
  290. // if (this.options.roomId) {
  291. // this.role = 'leader'
  292. // }
  293. // console.log('**************')
  294. // console.log(this.options)
  295. // }
  296. let isAllowMic // 真正MIC权, 房主与 授权一个 要在房间isAllowMic开启
  297. if (Number(isAnchor) === 1) {
  298. this.role = "leader"
  299. isAllowMic = 1
  300. } else {
  301. this.role = 'customer'
  302. isAllowMic = 0
  303. }
  304. // 助手改用isAssistant作为flag, role因为V3不能新增角色,只支持leader/customer。
  305. let isAssistant
  306. if (assistant && assistant.userId && assistant.userId == userInfo.userId) {
  307. isAssistant = true;
  308. } else {
  309. isAssistant = false
  310. }
  311. console.log('进入房间角色, 是否助手 %s', this.role, isAssistant);
  312. const isAuthMic = await this.getAuthorizeRecordStatus();
  313. // console.log('当前用户录音权限状态', isAuthMic)
  314. this.setData({
  315. isAllowMic,
  316. isAuthMic
  317. })
  318. const assistantId = (assistant && assistant.userId) ? assistant.userId : '';
  319. if (capacities) {
  320. this.setData({
  321. peopleCount: capacities
  322. })
  323. } else {
  324. this.setData({
  325. peopleCount: manyCount
  326. })
  327. }
  328. return {
  329. role: this.role,
  330. userId: userInfo.userId,
  331. // roomType,
  332. avatar: userInfo.avatarUrl,
  333. nickname: userInfo.nickname,
  334. voiceStatus: getApp().globalData.voiceProps.noMute ? 0 : 2,
  335. isAuthMic: isAuthMic ? 1 : 0,
  336. isAllowMic: isAllowMic,
  337. roomId: roomId,
  338. sceneNumber: sceneId,
  339. onlineStatus: 1,
  340. assistantId: assistantId,
  341. isAssistant: isAssistant ? 1 : 0,
  342. oid: userInfo.weixin_openid,
  343. userLimitNum: capacities || 50
  344. }
  345. },
  346. async socketStart({
  347. sceneId,
  348. roomId,
  349. options
  350. }) {
  351. if (!options) {
  352. options = await this.getSocketOptions(sceneId, roomId)
  353. }
  354. console.log('小程序参数', options)
  355. if (!options.roomId) {
  356. return
  357. }
  358. let userInfo = await this.getUserInfo()
  359. let socket = io(remote.socketHost, {
  360. path: '/fsl-node',
  361. transport: ['websocket'],
  362. extraHeaders: {
  363. "oid": userInfo.weixin_openid
  364. },
  365. query: {
  366. ...options,
  367. isClient: true,
  368. from: 2
  369. }
  370. })
  371. console.error('新建socket Room', options.roomId)
  372. this.setData({
  373. socketStatus: 0
  374. })
  375. socket.on('connect', () => this.setData({
  376. socketStatus: 1
  377. }))
  378. socket.on('connect_error', () => this.setData({
  379. socketStatus: -1
  380. }))
  381. socket.on('connect_timeout', () => this.setData({
  382. socketStatus: -1
  383. }))
  384. socket.on('disconnect', () => this.setData({
  385. socketStatus: -1
  386. }))
  387. socket.on('reconnect', () => {
  388. // wx.showToast({
  389. // title: '重连',
  390. // })
  391. this.setData({
  392. socketStatus: this.data.socketStatus
  393. })
  394. let noMute = getApp().globalData.voiceProps.noMute
  395. this.socketSendMessage('changeVoiceStatus', {
  396. status: noMute ? 0 : 2
  397. })
  398. this.socketSendMessage('changeOnlineStatus', {
  399. status: 1
  400. })
  401. })
  402. socket.on('reconnect_failed', () => this.setData({
  403. socketStatus: -1
  404. }))
  405. socket.on('error', () => this.setData({
  406. socketStatus: -1
  407. }))
  408. socket.on('roomIn', config => {
  409. let enableTalk = config.roomsConfig.enableTalk !== false
  410. let noMute = getApp().globalData.voiceProps.noMute
  411. getApp().globalData.voiceProps.force = enableTalk
  412. if (!enableTalk && !noMute) {
  413. if (this.role !== 'leader') {
  414. // this.mic()
  415. }
  416. }
  417. })
  418. this.socketSendMessage = (event, obj) => {
  419. console.error('发送 socket Room', options.roomId, event, obj)
  420. socket.emit(event, obj)
  421. }
  422. socket.on('clientSyncAction', (data) => {
  423. console.log('调用', data.type, '方法', data)
  424. if (this[data.type]) {
  425. this[data.type](data)
  426. } else if (data.type == 'wx-subscribe') {
  427. this.getUrlCode(data.data)
  428. } else {
  429. console.error('没有', data.type, '方法')
  430. }
  431. })
  432. socket.on('action', (data) => {
  433. if (data.type === 'navigateToGoods') {
  434. this.navigateToGoodsAction(data.data)
  435. }
  436. })
  437. socket.on('changeRoomEnableTalk', config => {
  438. if (this.role !== 'leader') {
  439. this.changeRoomEnableTalk(config)
  440. }
  441. })
  442. socket.on('startCall', this.startCall.bind(this))
  443. socket.on('stopCall', (data) => {
  444. console.log('on stopCall')
  445. this.stopCall(data)
  446. })
  447. this.handleSomeOneInRoom = this.handleSomeOneInRoom.bind(this)
  448. // socket.on('someOneInRoom', debounce(this.handleSomeOneInRoom, 100))
  449. socket.on('someOneInRoom', debounce(this.handleSomeOneInRoom, 100))
  450. socket.on('someOneLeaveRoom', (user, data) => {
  451. this.handleSomeOneLeave(user)
  452. })
  453. socket.on('roomClose', (data) => {
  454. console.log('on roomClose')
  455. this.stopCall(data)
  456. })
  457. socket.on('autoReJoin', (data) => {
  458. console.log('on autoReJoin')
  459. if ('roomId' in data) {
  460. options.roomId = Number(data.roomId)
  461. }
  462. })
  463. // 有MIC通知,主要是其他用户禁MIC 移到中间层处理。
  464. // socket.on('beHasMic', (data) => {
  465. // const socketOptions = this.data.socketOptions
  466. // if (data.user) {
  467. // const isOther = (socketOptions.role !== 'leader' && (Number(socketOptions.userId) !== Number(data.user.userId)));
  468. // if (isOther) {
  469. // this.closeMic();
  470. // // wx.showToast({
  471. // // title: '关mic' + isOther
  472. // // })
  473. // }
  474. // }
  475. // })
  476. socket.on("beKicked", data => {
  477. const that = this
  478. if (data.userId && data.roomId) {
  479. const socketOptions = this.data.socketOptions
  480. const userId = data.userId
  481. const roomId = data.roomId
  482. // debugger
  483. if (socketOptions.userId == userId && this.options.roomId == roomId) {
  484. wx.showToast({
  485. title: '您已被踢出房间!',
  486. icon: 'none',
  487. complete: () => {}
  488. })
  489. setTimeout(() => {
  490. that.socketStop();
  491. wx.switchTab({
  492. url: '/pages/index/index',
  493. })
  494. }, 1000)
  495. }
  496. }
  497. });
  498. socket.on("roomMaximum", () => {
  499. this.setData({
  500. roomMaximum: true
  501. })
  502. });
  503. //全员退出
  504. socket.on('roomDisMiss', () => {
  505. // wx.showToast({
  506. // title: '全员退出',
  507. // });
  508. this.setData({
  509. roomDisMiss: true
  510. })
  511. // this.exitRoom();
  512. })
  513. //服务器未知错误重进
  514. socket.on('unKnowError', () => {
  515. this.setData({
  516. unKnowError: true
  517. })
  518. })
  519. //被动通知开关MIC 要3秒后
  520. socket.on('serverOnMic', ({
  521. voiceStatus
  522. }) => {
  523. setTimeout(() => {
  524. if (Number(voiceStatus) === 2) {
  525. // wx.showToast({
  526. // title: '开MIC',
  527. // icon:'none'
  528. // })
  529. this.openMic();
  530. }
  531. if (Number(voiceStatus) === 0) {
  532. // wx.showToast({
  533. // title: '关MIC',
  534. // icon:'none'
  535. // })
  536. this.closeMic();
  537. }
  538. }, 3000)
  539. });
  540. this.socketStop = () => {
  541. if (socket) {
  542. socket.close()
  543. console.error('断开 并滞空 socket Room', options.roomId)
  544. this.setData({
  545. socketStatus: 2
  546. })
  547. socket = null
  548. }
  549. }
  550. return options
  551. },
  552. getUrlCode(url) {
  553. this.socketSendMessage('clientSyncAction', {
  554. sender: 'wx',
  555. type: 'wx-subscribe-result',
  556. data: 3020
  557. })
  558. // wx.request({
  559. // url: url, //仅为示例,并非真实的接口地址
  560. // method: 'get',
  561. // success: (res) => {
  562. // let code = -1
  563. // if (typeof res.data.code != 'undefined') {
  564. // code = res.data.code
  565. // }
  566. // this.socketSendMessage('clientSyncAction', {
  567. // sender: 'wx',
  568. // type: 'wx-subscribe-result',
  569. // data: code
  570. // })
  571. // },
  572. // fail: (err) => {
  573. // console.log(err)
  574. // }
  575. // })
  576. },
  577. changeRoomEnableTalk(data) {
  578. console.log(data)
  579. let noMute = getApp().globalData.voiceProps.noMute
  580. getApp().globalData.voiceProps.force = data.enableTalk
  581. // noMute true 静音
  582. // enableTalk false 静音
  583. if (!!data.enableTalk === !!noMute) {
  584. this.mic()
  585. }
  586. },
  587. navigateToGoods({
  588. data
  589. }) {
  590. // wx.showToast({
  591. // title: JSON.stringify(data).substr(40)
  592. // })
  593. this.navigateToGoodsAction(data)
  594. },
  595. navigateToGoodsAction(id) {
  596. wx.navigateTo({
  597. url: '/pages/goods/goods?id=' + id,
  598. })
  599. },
  600. getUrl(url, socketOptions, isJoin) {
  601. url += '&room_id=' + socketOptions.roomId + '&user_id=' + socketOptions.userId + '&origin=fashilong'
  602. if (isJoin) {
  603. url += '&role=' + this.role + '&shopping'
  604. } else {
  605. url += '&role=' + this.role
  606. }
  607. console.error(url)
  608. console.log(isJoin)
  609. return url
  610. },
  611. navigateToMiniProgram(data) {
  612. wx.showModal({
  613. title: '温馨提示',
  614. content: '即将跳到其他小程序,是否继续?',
  615. showCancel: true, //是否显示取消按钮
  616. cancelText: "取消", //默认是“取消”
  617. confirmText: "确定", //默认是“确定”
  618. success: function (res) {
  619. if (res.cancel) {
  620. //点击取消,wx.navigateBack
  621. } else {
  622. wx.navigateToMiniProgram(data.data)
  623. }
  624. },
  625. fail: function (res) {
  626. //接口调用失败的回调函数,wx.navigateBack
  627. },
  628. complete: function (res) {
  629. //接口调用结束的回调函数(调用成功、失败都会执行)
  630. },
  631. })
  632. },
  633. async handleSomeOneInRoom(data) {
  634. if (data && data.user) {
  635. console.log('handleSomeOneInRoom', data)
  636. this.startCall(data)
  637. }
  638. },
  639. async startCall(data) {
  640. //TODO 触发三次
  641. console.log('startCall-data', data)
  642. // if( this.role =='leader'){
  643. this.setData({
  644. shareStatus: 1
  645. })
  646. if (!data) return;
  647. this.setData({
  648. surplus: this.data.peopleCount - data.roomsPerson.length
  649. })
  650. //undefined是未授权,状态为3
  651. let voiceStatus
  652. if (!this.isAuthorizeRecord) {
  653. const unAuth = await this.authorizeRecord();
  654. if (typeof unAuth === 'undefined') {
  655. // debugger
  656. voiceStatus = 3
  657. } else {
  658. voiceStatus = Number(unAuth)
  659. }
  660. }
  661. //限制只有主持人才可以开麦
  662. // if (this.role == 'leader') {
  663. // if (!this.isAuthorizeRecord) {
  664. // const voiceStatus = Number(await this.authorizeRecord())
  665. // this.isAuthorizeRecord = true
  666. // // getApp().setVoiceProps({
  667. // // noMute: !voiceStatus
  668. // // })
  669. // // console.log(getApp().globalData.voiceProps.noMute)
  670. // // this.socketSendMessage('changeVoiceStatus', {
  671. // // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  672. // // })
  673. // // this.data.socketOptions.voiceStatus = 1
  674. // // this.socketSendMessage('changeVoiceStatus', {status: noMute ? 0 : 2})
  675. // }
  676. // }
  677. const socketOptions = this.data.socketOptions
  678. getApp().globalData.roomId = socketOptions.roomId
  679. const user = data.roomsPerson.find(user => user.userId == socketOptions.userId)
  680. if (!user) {
  681. return
  682. }
  683. //屏蔽有人进来才开麦克风
  684. // if (data.roomsPerson.length <= 1) {
  685. // return
  686. // }
  687. user.noMute = getApp().globalData.voiceProps.noMute
  688. getApp().setVoiceProps({
  689. ...user,
  690. action: 'startCall'
  691. })
  692. // this.socketSendMessage('changeVoiceStatus', {
  693. // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  694. // })
  695. // }
  696. },
  697. stopCall() {
  698. console.error('stopCall')
  699. this.setData({
  700. shareStatus: 0
  701. })
  702. getApp().setVoiceProps({
  703. noMute: false,
  704. action: 'stopCall'
  705. })
  706. if (this.runManager) {
  707. // this.recorderManager.stop()
  708. this.runManager = false
  709. }
  710. },
  711. handleSomeOneLeave(data) {
  712. if (data.roomsPerson.length <= 1) {
  713. // this.stopCall()
  714. }
  715. this.setData({
  716. surplus: this.data.peopleCount - data.roomsPerson.length
  717. })
  718. },
  719. //deprecated
  720. async newRoomBk(data) {
  721. if (data.roomId) return;
  722. this.stopCall()
  723. getApp().globalData.rtcParams = []
  724. getApp().globalData.pusher = ''
  725. if (this.data.join && !this.options.join) {
  726. wx.switchTab({
  727. url: '/pages/index/index',
  728. })
  729. return;
  730. }
  731. this.role = this.data.canShow ? 'leader' : 'customer'
  732. let options = await this.getSocketOptions(this.mcode)
  733. this.socketSendMessage('clientSyncAction', {
  734. type: 'newRoom',
  735. data: options
  736. })
  737. setTimeout(async () => {
  738. this.wssSuccess = false
  739. this.socketStop && this.socketStop()
  740. this.data.many = !!this.data.canShow
  741. // this.setData({
  742. // // peopleCount: this.data.many ? manyCount : 5
  743. // peopleCount: manyCount
  744. // })
  745. let base = this.base
  746. let socketOptions = await this.socketStart({
  747. options
  748. })
  749. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  750. this.base = base
  751. this.setData({
  752. url,
  753. socketOptions,
  754. })
  755. this.joinUrl()
  756. this.setData({
  757. socketOptions
  758. })
  759. this.loadConponSuccess = true
  760. this.readySendCouponCtrl()
  761. }, 300)
  762. },
  763. // 真正退出房间
  764. async exitRoom() {
  765. const roomId = this.data.socketOptions.roomId;
  766. const role = this.role;
  767. const result = await util.request(api.exitRoom, {
  768. businessId: roomId
  769. }, 'POST', 'application/json');
  770. this.socketSendMessage('stopCall', {
  771. from: 2
  772. })
  773. this.stopCall();
  774. this.socketStop();
  775. if (role === 'leader') {
  776. wx.redirectTo({
  777. url: '/pages/roomManger/roomManger',
  778. });
  779. } else {
  780. wx.switchTab({
  781. url: '/pages/index/index'
  782. });
  783. }
  784. },
  785. async exit() {
  786. // this.stopCall()
  787. getApp().globalData.rtcParams = []
  788. getApp().globalData.pusher = ''
  789. this.socketStop && this.socketStop()
  790. this.role = 'leader'
  791. let base = this.base
  792. let socketOptions = await this.socketStart({
  793. sceneId: this.mcode
  794. })
  795. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  796. this.base = base
  797. wx.nextTick(() => {
  798. setTimeout(() => {
  799. this.setData({
  800. url,
  801. loadUrl: true,
  802. socketOptions,
  803. showCommodityCtrl: false,
  804. hideWebView: false,
  805. reload: true
  806. })
  807. this.joinUrl()
  808. }, 500)
  809. })
  810. },
  811. clearDebuger() {
  812. this.setData({
  813. debugerInfo: ''
  814. })
  815. },
  816. async mic({
  817. data
  818. }) {
  819. if (Number(data.user.isAllowMic) === 1) {
  820. let noMute = getApp().globalData.voiceProps.noMute
  821. // debugger
  822. // noMute true 静音
  823. // enableTalk false 静音
  824. // if (!!getApp().globalData.voiceProps.force === !!noMute)
  825. // return
  826. // if (!getApp().globalData.voiceProps.force && (!this.data.socketOptions.voiceStatus || noMute)) return;
  827. if (!this.data.socketOptions.voiceStatus) {
  828. let voiceStatus = await this.authorizeRecord()
  829. if (voiceStatus) {
  830. this.data.socketOptions.voiceStatus = 1
  831. noMute = false
  832. } else {
  833. noMute = true
  834. }
  835. } else {
  836. noMute = !noMute
  837. }
  838. getApp().globalData.voiceProps.noMute = noMute
  839. this.socketSendMessage('changeVoiceStatus', {
  840. status: noMute ? 0 : 2,
  841. user: data.user
  842. })
  843. getApp().setVoiceProps({
  844. noMute
  845. })
  846. wx.showToast({
  847. title: `已${noMute ? '关闭' : '开启'}麦克风`,
  848. })
  849. }
  850. },
  851. closeMic() {
  852. getApp().globalData.voiceProps.noMute = true
  853. this.socketSendMessage('changeVoiceStatus', {
  854. status: 0,
  855. })
  856. getApp().setVoiceProps({
  857. noMute: true
  858. })
  859. },
  860. openMic() {
  861. getApp().globalData.voiceProps.noMute = false
  862. this.socketSendMessage('changeVoiceStatus', {
  863. status: 2,
  864. })
  865. getApp().setVoiceProps({
  866. noMute: false
  867. })
  868. },
  869. callPhone() {
  870. wx.makePhoneCall({
  871. phoneNumber: this.data.contractPhone,
  872. })
  873. this.setData({
  874. showContact: false
  875. })
  876. },
  877. /**
  878. * 用户点击右上角分享
  879. */
  880. onShareAppMessage: function (res) {
  881. let {
  882. id,
  883. newPicUrl
  884. } = this.data
  885. if (res.from === 'button') {
  886. this.setData({
  887. sendShare: false
  888. })
  889. return {
  890. title: '【好友推荐】一起来云逛吧',
  891. imageUrl: newPicUrl,
  892. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=true&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`,
  893. }
  894. } else {
  895. return {
  896. imageUrl: newPicUrl,
  897. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=false`,
  898. }
  899. }
  900. },
  901. /**
  902. * 生命周期函数--监听页面卸载
  903. */
  904. onUnload: function () {
  905. console.log('on onUnload')
  906. // this.socketSendMessage('stopCall', {})
  907. // this.stopCall()
  908. this.socketStop && this.socketStop()
  909. getApp().globalData.pusher = ''
  910. },
  911. cart(data) {
  912. this.setData({
  913. showCommodityCtrl: data.data
  914. })
  915. },
  916. share() {
  917. console.log('share-debug')
  918. const companyName = `指房宝(杭州)科技有限公司`
  919. const vrLink = `/pages/webview/index`
  920. const img_url = this.data.newPicUrl || 'http://video.cgaii.com/new4dage/images/images/home_2_a.jpg'
  921. const shareImg = img_url
  922. this.count = this.count || 0
  923. console.log('share-debug many:%s shareStatus: %s', !!this.data.many, this.data.shareStatus);
  924. // debugger;
  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. util.request(api.BrandDetail, {
  1202. id: id,
  1203. type: type,
  1204. }).then((res) => {
  1205. let base = res.data.brand.sceneUrl
  1206. // let base = 'http://192.168.0.112:8080/shop.html?m=t-7Uqj9Fq&origin=fashilong'
  1207. if (res.errno === 0) {
  1208. let url = base + "&sid=" + id
  1209. this.setData({
  1210. id: id,
  1211. newPicUrl: res.data.brand.appListPicUrl,
  1212. sceneNum: res.data.brand.sceneNum,
  1213. canShow: res.data.brand.canShow,
  1214. contractPhone: res.data.brand.contractPhone
  1215. })
  1216. // debugger
  1217. if (this.data.many === void 0) {
  1218. this.data.many = !!res.data.brand.canShow
  1219. }
  1220. this.setData({
  1221. // peopleCount: this.data.many ? manyCount : 5,
  1222. peopleCount: manyCount
  1223. })
  1224. if (!res.data.brand.canShow) {
  1225. this.role = 'customer'
  1226. } else if (!this.options.join) {
  1227. this.role = 'leader'
  1228. }
  1229. cb(url, urlToJson(url).m, )
  1230. }
  1231. });
  1232. },
  1233. selectType(ev) {
  1234. this.getGoodsList(this.options.id, ev.target.dataset.item.category_id)
  1235. },
  1236. hideCS() {
  1237. this.setData({
  1238. showCommodity: false,
  1239. showCoupon: false,
  1240. showContact: false
  1241. })
  1242. },
  1243. hideContact() {
  1244. this.setData({
  1245. showContact: false
  1246. })
  1247. },
  1248. calcShare() {
  1249. // this.exit()
  1250. this.setData({
  1251. sendShare: false
  1252. })
  1253. },
  1254. contactKf() {
  1255. let keys = Object.keys(this.navDatas)
  1256. let goodsId = this.navDatas[keys[0]][0].id
  1257. let user = wx.getStorageSync('userinfoDetail')
  1258. util.request(api.AddTalkCount, {
  1259. goodsId,
  1260. viewId: user && user.userId || '',
  1261. sceneNum: this.data.sceneNum
  1262. }, 'get')
  1263. this.hideAlert && this.hideAlert()
  1264. this.hideContact && this.hideContact()
  1265. },
  1266. onHide() {
  1267. this.socketSendMessage('changeOnlineStatus', {
  1268. status: 0
  1269. })
  1270. this.pauseVideo = true
  1271. this.joinUrl()
  1272. }
  1273. }