socket.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  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 socket = io(remote.socketHost, {
  359. path: '/fsl-node',
  360. transport: ['websocket'],
  361. query: {
  362. ...options,
  363. isClient: true,
  364. from: 2
  365. }
  366. })
  367. console.error('新建socket Room', options.roomId)
  368. this.setData({
  369. socketStatus: 0
  370. })
  371. socket.on('connect', () => this.setData({
  372. socketStatus: 1
  373. }))
  374. socket.on('connect_error', () => this.setData({
  375. socketStatus: -1
  376. }))
  377. socket.on('connect_timeout', () => this.setData({
  378. socketStatus: -1
  379. }))
  380. socket.on('disconnect', () => this.setData({
  381. socketStatus: -1
  382. }))
  383. socket.on('reconnect', () => {
  384. // wx.showToast({
  385. // title: '重连',
  386. // })
  387. this.setData({
  388. socketStatus: this.data.socketStatus
  389. })
  390. let noMute = getApp().globalData.voiceProps.noMute
  391. this.socketSendMessage('changeVoiceStatus', {
  392. status: noMute ? 0 : 2
  393. })
  394. this.socketSendMessage('changeOnlineStatus', {
  395. status: 1
  396. })
  397. })
  398. socket.on('reconnect_failed', () => this.setData({
  399. socketStatus: -1
  400. }))
  401. socket.on('error', () => this.setData({
  402. socketStatus: -1
  403. }))
  404. socket.on('roomIn', config => {
  405. let enableTalk = config.roomsConfig.enableTalk !== false
  406. let noMute = getApp().globalData.voiceProps.noMute
  407. getApp().globalData.voiceProps.force = enableTalk
  408. if (!enableTalk && !noMute) {
  409. if (this.role !== 'leader') {
  410. // this.mic()
  411. }
  412. }
  413. })
  414. this.socketSendMessage = (event, obj) => {
  415. console.error('发送 socket Room', options.roomId, event, obj)
  416. socket.emit(event, obj)
  417. }
  418. socket.on('clientSyncAction', (data) => {
  419. console.log('调用', data.type, '方法', data)
  420. if (this[data.type]) {
  421. this[data.type](data)
  422. } else if (data.type == 'wx-subscribe') {
  423. this.getUrlCode(data.data)
  424. } else {
  425. console.error('没有', data.type, '方法')
  426. }
  427. })
  428. socket.on('action', (data) => {
  429. if (data.type === 'navigateToGoods') {
  430. this.navigateToGoodsAction(data.data)
  431. }
  432. })
  433. socket.on('changeRoomEnableTalk', config => {
  434. if (this.role !== 'leader') {
  435. this.changeRoomEnableTalk(config)
  436. }
  437. })
  438. socket.on('startCall', this.startCall.bind(this))
  439. socket.on('stopCall', (data) => {
  440. console.log('on stopCall')
  441. this.stopCall(data)
  442. })
  443. this.handleSomeOneInRoom = this.handleSomeOneInRoom.bind(this)
  444. // socket.on('someOneInRoom', debounce(this.handleSomeOneInRoom, 100))
  445. socket.on('someOneInRoom', debounce(this.handleSomeOneInRoom, 100))
  446. socket.on('someOneLeaveRoom', (user, data) => {
  447. this.handleSomeOneLeave(user)
  448. })
  449. socket.on('roomClose', (data) => {
  450. console.log('on roomClose')
  451. this.stopCall(data)
  452. })
  453. socket.on('autoReJoin', (data) => {
  454. console.log('on autoReJoin')
  455. if ('roomId' in data) {
  456. options.roomId = Number(data.roomId)
  457. }
  458. })
  459. // 有MIC通知,主要是其他用户禁MIC 移到中间层处理。
  460. // socket.on('beHasMic', (data) => {
  461. // const socketOptions = this.data.socketOptions
  462. // if (data.user) {
  463. // const isOther = (socketOptions.role !== 'leader' && (Number(socketOptions.userId) !== Number(data.user.userId)));
  464. // if (isOther) {
  465. // this.closeMic();
  466. // // wx.showToast({
  467. // // title: '关mic' + isOther
  468. // // })
  469. // }
  470. // }
  471. // })
  472. socket.on("beKicked", data => {
  473. const that = this
  474. if (data.userId && data.roomId) {
  475. const socketOptions = this.data.socketOptions
  476. const userId = data.userId
  477. const roomId = data.roomId
  478. // debugger
  479. if (socketOptions.userId == userId && this.options.roomId == roomId) {
  480. wx.showToast({
  481. title: '您已被踢出房间!',
  482. icon: 'none',
  483. complete: () => {}
  484. })
  485. setTimeout(() => {
  486. that.socketStop();
  487. wx.switchTab({
  488. url: '/pages/index/index',
  489. })
  490. }, 1000)
  491. }
  492. }
  493. });
  494. socket.on("roomMaximum", () => {
  495. this.setData({
  496. roomMaximum: true
  497. })
  498. });
  499. //被动通知开关MIC
  500. socket.on('serverOnMic', ({
  501. voiceStatus
  502. }) => {
  503. setTimeout(() => {
  504. if (Number(voiceStatus) === 2) {
  505. this.openMic();
  506. }
  507. if (Number(voiceStatus) === 0) {
  508. this.closeMic();
  509. }
  510. }, 1000)
  511. })
  512. this.socketStop = () => {
  513. if (socket) {
  514. socket.close()
  515. console.error('断开 并滞空 socket Room', options.roomId)
  516. this.setData({
  517. socketStatus: 2
  518. })
  519. socket = null
  520. }
  521. }
  522. return options
  523. },
  524. getUrlCode(url) {
  525. this.socketSendMessage('clientSyncAction', {
  526. sender: 'wx',
  527. type: 'wx-subscribe-result',
  528. data: 3020
  529. })
  530. // wx.request({
  531. // url: url, //仅为示例,并非真实的接口地址
  532. // method: 'get',
  533. // success: (res) => {
  534. // let code = -1
  535. // if (typeof res.data.code != 'undefined') {
  536. // code = res.data.code
  537. // }
  538. // this.socketSendMessage('clientSyncAction', {
  539. // sender: 'wx',
  540. // type: 'wx-subscribe-result',
  541. // data: code
  542. // })
  543. // },
  544. // fail: (err) => {
  545. // console.log(err)
  546. // }
  547. // })
  548. },
  549. changeRoomEnableTalk(data) {
  550. console.log(data)
  551. let noMute = getApp().globalData.voiceProps.noMute
  552. getApp().globalData.voiceProps.force = data.enableTalk
  553. // noMute true 静音
  554. // enableTalk false 静音
  555. if (!!data.enableTalk === !!noMute) {
  556. this.mic()
  557. }
  558. },
  559. navigateToGoods({
  560. data
  561. }) {
  562. // wx.showToast({
  563. // title: JSON.stringify(data).substr(40)
  564. // })
  565. this.navigateToGoodsAction(data)
  566. },
  567. navigateToGoodsAction(id) {
  568. wx.navigateTo({
  569. url: '/pages/goods/goods?id=' + id,
  570. })
  571. },
  572. getUrl(url, socketOptions, isJoin) {
  573. url += '&room_id=' + socketOptions.roomId + '&user_id=' + socketOptions.userId + '&origin=fashilong'
  574. if (isJoin) {
  575. url += '&role=' + this.role + '&shopping'
  576. } else {
  577. url += '&role=' + this.role
  578. }
  579. console.error(url)
  580. console.log(isJoin)
  581. return url
  582. },
  583. navigateToMiniProgram(data) {
  584. wx.showModal({
  585. title: '温馨提示',
  586. content: '即将跳到其他小程序,是否继续?',
  587. showCancel: true, //是否显示取消按钮
  588. cancelText: "取消", //默认是“取消”
  589. confirmText: "确定", //默认是“确定”
  590. success: function (res) {
  591. if (res.cancel) {
  592. //点击取消,wx.navigateBack
  593. } else {
  594. wx.navigateToMiniProgram(data.data)
  595. }
  596. },
  597. fail: function (res) {
  598. //接口调用失败的回调函数,wx.navigateBack
  599. },
  600. complete: function (res) {
  601. //接口调用结束的回调函数(调用成功、失败都会执行)
  602. },
  603. })
  604. },
  605. async handleSomeOneInRoom(data) {
  606. if (data && data.user) {
  607. console.log('handleSomeOneInRoom', data)
  608. this.startCall(data)
  609. }
  610. },
  611. async startCall(data) {
  612. //TODO 触发三次
  613. console.log('startCall-data', data)
  614. // if( this.role =='leader'){
  615. this.setData({
  616. shareStatus: 1
  617. })
  618. if (!data) return;
  619. this.setData({
  620. surplus: this.data.peopleCount - data.roomsPerson.length
  621. })
  622. //undefined是未授权,状态为3
  623. let voiceStatus
  624. if (!this.isAuthorizeRecord) {
  625. const unAuth = await this.authorizeRecord();
  626. if (typeof unAuth === 'undefined') {
  627. // debugger
  628. voiceStatus = 3
  629. } else {
  630. voiceStatus = Number(unAuth)
  631. }
  632. }
  633. //限制只有主持人才可以开麦
  634. // if (this.role == 'leader') {
  635. // if (!this.isAuthorizeRecord) {
  636. // const voiceStatus = Number(await this.authorizeRecord())
  637. // this.isAuthorizeRecord = true
  638. // // getApp().setVoiceProps({
  639. // // noMute: !voiceStatus
  640. // // })
  641. // // console.log(getApp().globalData.voiceProps.noMute)
  642. // // this.socketSendMessage('changeVoiceStatus', {
  643. // // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  644. // // })
  645. // // this.data.socketOptions.voiceStatus = 1
  646. // // this.socketSendMessage('changeVoiceStatus', {status: noMute ? 0 : 2})
  647. // }
  648. // }
  649. const socketOptions = this.data.socketOptions
  650. getApp().globalData.roomId = socketOptions.roomId
  651. const user = data.roomsPerson.find(user => user.userId == socketOptions.userId)
  652. if (!user) {
  653. return
  654. }
  655. //屏蔽有人进来才开麦克风
  656. // if (data.roomsPerson.length <= 1) {
  657. // return
  658. // }
  659. user.noMute = getApp().globalData.voiceProps.noMute
  660. getApp().setVoiceProps({
  661. ...user,
  662. action: 'startCall'
  663. })
  664. // this.socketSendMessage('changeVoiceStatus', {
  665. // status: getApp().globalData.voiceProps.noMute ? 0 : 2
  666. // })
  667. // }
  668. },
  669. stopCall() {
  670. console.error('stopCall')
  671. this.setData({
  672. shareStatus: 0
  673. })
  674. getApp().setVoiceProps({
  675. noMute: false,
  676. action: 'stopCall'
  677. })
  678. if (this.runManager) {
  679. // this.recorderManager.stop()
  680. this.runManager = false
  681. }
  682. },
  683. handleSomeOneLeave(data) {
  684. if (data.roomsPerson.length <= 1) {
  685. // this.stopCall()
  686. }
  687. this.setData({
  688. surplus: this.data.peopleCount - data.roomsPerson.length
  689. })
  690. },
  691. //deprecated
  692. async newRoomBk(data) {
  693. if (data.roomId) return;
  694. this.stopCall()
  695. getApp().globalData.rtcParams = []
  696. getApp().globalData.pusher = ''
  697. if (this.data.join && !this.options.join) {
  698. wx.switchTab({
  699. url: '/pages/index/index',
  700. })
  701. return;
  702. }
  703. this.role = this.data.canShow ? 'leader' : 'customer'
  704. let options = await this.getSocketOptions(this.mcode)
  705. this.socketSendMessage('clientSyncAction', {
  706. type: 'newRoom',
  707. data: options
  708. })
  709. setTimeout(async () => {
  710. this.wssSuccess = false
  711. this.socketStop && this.socketStop()
  712. this.data.many = !!this.data.canShow
  713. // this.setData({
  714. // // peopleCount: this.data.many ? manyCount : 5
  715. // peopleCount: manyCount
  716. // })
  717. let base = this.base
  718. let socketOptions = await this.socketStart({
  719. options
  720. })
  721. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  722. this.base = base
  723. this.setData({
  724. url,
  725. socketOptions,
  726. })
  727. this.joinUrl()
  728. this.setData({
  729. socketOptions
  730. })
  731. this.loadConponSuccess = true
  732. this.readySendCouponCtrl()
  733. }, 300)
  734. },
  735. // 真正退出房间
  736. async exitRoom() {
  737. const roomId = this.data.socketOptions.roomId;
  738. const role = this.role;
  739. const result = await util.request(api.exitRoom, {
  740. businessId: roomId
  741. }, 'POST', 'application/json');
  742. this.socketSendMessage('stopCall', {
  743. from: 2
  744. })
  745. this.stopCall();
  746. this.socketStop();
  747. if (role === 'leader') {
  748. wx.redirectTo({
  749. url: '/pages/roomManger/roomManger',
  750. });
  751. } else {
  752. wx.switchTab({
  753. url: '/pages/index/index'
  754. });
  755. }
  756. },
  757. async exit() {
  758. // this.stopCall()
  759. getApp().globalData.rtcParams = []
  760. getApp().globalData.pusher = ''
  761. this.socketStop && this.socketStop()
  762. this.role = 'leader'
  763. let base = this.base
  764. let socketOptions = await this.socketStart({
  765. sceneId: this.mcode
  766. })
  767. let url = this.getUrl(base, socketOptions, false) + (this.urlPj || '')
  768. this.base = base
  769. wx.nextTick(() => {
  770. setTimeout(() => {
  771. this.setData({
  772. url,
  773. loadUrl: true,
  774. socketOptions,
  775. showCommodityCtrl: false,
  776. hideWebView: false,
  777. reload: true
  778. })
  779. this.joinUrl()
  780. }, 500)
  781. })
  782. },
  783. clearDebuger() {
  784. this.setData({
  785. debugerInfo: ''
  786. })
  787. },
  788. async mic({
  789. data
  790. }) {
  791. if (Number(data.user.isAllowMic) === 1) {
  792. let noMute = getApp().globalData.voiceProps.noMute
  793. // debugger
  794. // noMute true 静音
  795. // enableTalk false 静音
  796. // if (!!getApp().globalData.voiceProps.force === !!noMute)
  797. // return
  798. // if (!getApp().globalData.voiceProps.force && (!this.data.socketOptions.voiceStatus || noMute)) return;
  799. if (!this.data.socketOptions.voiceStatus) {
  800. let voiceStatus = await this.authorizeRecord()
  801. if (voiceStatus) {
  802. this.data.socketOptions.voiceStatus = 1
  803. noMute = false
  804. } else {
  805. noMute = true
  806. }
  807. } else {
  808. noMute = !noMute
  809. }
  810. getApp().globalData.voiceProps.noMute = noMute
  811. this.socketSendMessage('changeVoiceStatus', {
  812. status: noMute ? 0 : 2,
  813. user: data.user
  814. })
  815. getApp().setVoiceProps({
  816. noMute
  817. })
  818. wx.showToast({
  819. title: `已${noMute ? '关闭' : '开启'}麦克风`,
  820. })
  821. }
  822. },
  823. closeMic() {
  824. getApp().globalData.voiceProps.noMute = true
  825. this.socketSendMessage('changeVoiceStatus', {
  826. status: 0,
  827. })
  828. getApp().setVoiceProps({
  829. noMute: true
  830. })
  831. },
  832. openMic() {
  833. getApp().globalData.voiceProps.noMute = false
  834. this.socketSendMessage('changeVoiceStatus', {
  835. status: 2,
  836. })
  837. getApp().setVoiceProps({
  838. noMute: false
  839. })
  840. },
  841. callPhone() {
  842. wx.makePhoneCall({
  843. phoneNumber: this.data.contractPhone,
  844. })
  845. this.setData({
  846. showContact: false
  847. })
  848. },
  849. /**
  850. * 用户点击右上角分享
  851. */
  852. onShareAppMessage: function (res) {
  853. let {
  854. id,
  855. newPicUrl
  856. } = this.data
  857. if (res.from === 'button') {
  858. this.setData({
  859. sendShare: false
  860. })
  861. return {
  862. title: '【好友推荐】一起来云逛吧',
  863. imageUrl: newPicUrl,
  864. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=true&roomId=${this.data.socketOptions.roomId}&many=${!!this.data.many}`,
  865. }
  866. } else {
  867. return {
  868. imageUrl: newPicUrl,
  869. path: `/pages/webview/index?id=${id}&type=${this.data.type}&join=false`,
  870. }
  871. }
  872. },
  873. /**
  874. * 生命周期函数--监听页面卸载
  875. */
  876. onUnload: function () {
  877. console.log('on onUnload')
  878. // this.socketSendMessage('stopCall', {})
  879. // this.stopCall()
  880. this.socketStop && this.socketStop()
  881. getApp().globalData.pusher = ''
  882. },
  883. cart(data) {
  884. this.setData({
  885. showCommodityCtrl: data.data
  886. })
  887. },
  888. share() {
  889. console.log('share-debug')
  890. const companyName = `指房宝(杭州)科技有限公司`
  891. const vrLink = `/pages/webview/index`
  892. const img_url = this.data.newPicUrl || 'http://video.cgaii.com/new4dage/images/images/home_2_a.jpg'
  893. const shareImg = img_url
  894. this.count = this.count || 0
  895. console.log('share-debug many:%s shareStatus: %s', !!this.data.many, this.data.shareStatus);
  896. // debugger;
  897. if (this.data.many && this.data.shareStatus == 1) {
  898. //开启一起逛时候的分享
  899. 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}`)
  900. console.log('share-debug', this.data.socketOptions)
  901. wx.navigateTo({
  902. 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}`,
  903. })
  904. } else {
  905. 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}`);
  906. wx.navigateTo({
  907. 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}`,
  908. })
  909. }
  910. },
  911. back(data) {
  912. if (data.sender !== 'h5') return;
  913. wx.switchTab({
  914. url: '/pages/index/index'
  915. })
  916. this.setData({
  917. showCommodityCtrl: false
  918. })
  919. },
  920. service() {
  921. this.setData({
  922. showContact: true,
  923. showCommodity: false,
  924. showCoupon: false
  925. })
  926. },
  927. invite(data) {
  928. if (data.sender !== 'h5') return;
  929. this.setData({
  930. sendShare: true,
  931. count: ++this.data.count
  932. })
  933. },
  934. coupon(data) {
  935. if (data.sender !== 'h5') return;
  936. this.setData({
  937. showContact: false,
  938. showCommodity: false,
  939. showCoupon: true
  940. })
  941. },
  942. liveGotoGood(ev) {
  943. let id = ev.currentTarget.dataset.item.goodsId
  944. wx.navigateTo({
  945. url: '/pages/goods/goods?id=' + id,
  946. })
  947. },
  948. gotoGoodsDOM(event) {
  949. this.gotoGoods(event.currentTarget.dataset.item.hotIdList[0])
  950. },
  951. gotoGoodsSocket(data) {
  952. this.gotoGoods(data.data)
  953. },
  954. gotoGoods(id) {
  955. console.log('---', id)
  956. this.socketSendMessage('clientSyncAction', {
  957. type: 'openTag',
  958. data: id
  959. })
  960. this.setData({
  961. showCommodity: false
  962. })
  963. this.joinUrl()
  964. },
  965. addCard(event) {
  966. wx.navigateTo({
  967. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=addCard',
  968. })
  969. },
  970. buyGoods(event) {
  971. wx.navigateTo({
  972. url: '/pages/goods/goods?id=' + event.currentTarget.dataset.id + '&oper=buyGoods',
  973. })
  974. },
  975. showCommodityFn() {
  976. this.setData({
  977. showCommodity: true,
  978. showContact: false,
  979. showCoupon: false
  980. })
  981. this.joinUrl()
  982. },
  983. hideComodity() {
  984. this.setData({
  985. showCommodity: false
  986. })
  987. this.joinUrl()
  988. },
  989. hideCoupon() {
  990. this.setData({
  991. showCoupon: !this.data.showCoupon
  992. })
  993. },
  994. async receive(ev) {
  995. let item = ev.target.dataset.item
  996. try {
  997. // wx.showToast({
  998. // title: '领取优惠卷',
  999. // })
  1000. // return;
  1001. if (item.hasReceived || item.number <= item.receiveNumber) return;
  1002. let res = await util.request(api.CouponExchange, {
  1003. couponId: item.id
  1004. })
  1005. if (res.code === 0) {
  1006. wx.showToast({
  1007. title: '已成功领取',
  1008. success: () => {
  1009. this.setData({
  1010. showCoupon: false
  1011. })
  1012. wx.nextTick(() => {
  1013. this.setData({
  1014. coupons: this.data.coupons.map(citem => {
  1015. return {
  1016. ...citem,
  1017. hasReceived: citem.id === item.id ? true : citem.hasReceived
  1018. }
  1019. }),
  1020. showCoupon: true
  1021. })
  1022. })
  1023. }
  1024. })
  1025. } else if (res.errno === 401) {
  1026. getApp().setLoginProps(false)
  1027. } else {
  1028. wx.showToast({
  1029. title: res.msg,
  1030. })
  1031. }
  1032. } catch (e) {
  1033. console.error(e)
  1034. wx.showToast({
  1035. icon: 'none',
  1036. title: '领取失败',
  1037. })
  1038. }
  1039. },
  1040. async getCouponList(id) {
  1041. const success = (res) => {
  1042. this.setData({
  1043. coupons: res.data.list.map(item => {
  1044. item.typeMoney = item.typeMoney.toString()
  1045. item.fontSize = item.typeMoney.length === 3 ? '90rpx' :
  1046. item.typeMoney.length === 4 ? '70rpx' : '130rpx'
  1047. return item
  1048. })
  1049. })
  1050. this.loadConponSuccess = true
  1051. this.readySendCouponCtrl()
  1052. }
  1053. let res = await util.request(api.BrandCouponList, {
  1054. brandId: id,
  1055. pageNum: 1,
  1056. pageSize: 10000
  1057. }, 'GET')
  1058. console.log(res)
  1059. if (res.code === 0) {
  1060. success(res)
  1061. } else {
  1062. let res = await util.request(api.UNBrandCouponList, {
  1063. brandId: id,
  1064. pageNum: 1,
  1065. pageSize: 10000
  1066. }, 'GET')
  1067. success(res)
  1068. }
  1069. },
  1070. ready() {
  1071. this.wssSuccess = true
  1072. this.readySendCouponCtrl()
  1073. },
  1074. readySendCouponCtrl() {
  1075. if (this.wssSuccess && this.loadConponSuccess) {
  1076. this.loadConponSuccess = false
  1077. this.socketSendMessage('clientSyncAction', {
  1078. type: 'showCoupon',
  1079. data: this.data.coupons.length > 0
  1080. })
  1081. }
  1082. },
  1083. getBrand: function (id, code) {
  1084. this.getGoodsCount(code, id)
  1085. return;
  1086. },
  1087. getGoodsCount(code, id) {
  1088. util.request(api.GoodsNumCount, {
  1089. isDelete: 0,
  1090. isOnSale: 1,
  1091. brandId: id
  1092. }, 'GET')
  1093. .then(res => {
  1094. if (res.errno === 0) {
  1095. this.setData({
  1096. goodsCount: res.data
  1097. })
  1098. }
  1099. this.getCouponList(id)
  1100. })
  1101. },
  1102. getGoodsList(id, category_id) {
  1103. var that = this;
  1104. if (!(this.data.navList && this.data.navList.length)) {
  1105. that.navDatas = {}
  1106. let navDatas = this.data.navList = this.data.comtypes
  1107. // util.request(api.GoodsCategory, { id: category_id })
  1108. // .then(function (res) {
  1109. // if (res.errno == 0) {
  1110. // let navDatas = res.data.brotherCategory
  1111. // that.setData({
  1112. // navList: navDatas,
  1113. // currTypeId: category_id
  1114. // });
  1115. that.navDatas = {}
  1116. navDatas.forEach(item => {
  1117. util.request(api.GoodsList, {
  1118. brandId: id,
  1119. categoryId: item.category_id,
  1120. page: that.data.page,
  1121. size: that.data.size
  1122. })
  1123. .then(res => {
  1124. if (res.errno === 0) {
  1125. that.navDatas[item.category_id] = res.data.goodsList
  1126. }
  1127. })
  1128. })
  1129. // }
  1130. // })
  1131. }
  1132. if (that.navDatas[category_id]) {
  1133. if (!isIos) {
  1134. let showCommodity = that.data.showCommodity
  1135. that.setData({
  1136. showCommodity: false
  1137. })
  1138. setTimeout(() => {
  1139. wx.nextTick(() => {
  1140. that.setData({
  1141. goodsList: that.navDatas[category_id],
  1142. currTypeId: category_id,
  1143. showCommodity: showCommodity
  1144. });
  1145. })
  1146. }, 500)
  1147. } else {
  1148. that.setData({
  1149. goodsList: that.navDatas[category_id],
  1150. currTypeId: category_id,
  1151. });
  1152. }
  1153. } else {
  1154. console.error('诱惑去啦')
  1155. util.request(api.GoodsList, {
  1156. brandId: id,
  1157. categoryId: category_id,
  1158. page: that.data.page,
  1159. size: that.data.size
  1160. })
  1161. .then(function (res) {
  1162. if (res.errno === 0) {
  1163. that.setData({
  1164. goodsList: res.data.goodsList,
  1165. currTypeId: category_id
  1166. });
  1167. // this.data.navList
  1168. }
  1169. });
  1170. }
  1171. },
  1172. getBrandDetail: function (id, type, cb) {
  1173. util.request(api.BrandDetail, {
  1174. id: id,
  1175. type: type,
  1176. }).then((res) => {
  1177. let base = res.data.brand.sceneUrl
  1178. // let base = 'http://192.168.0.112:8080/shop.html?m=t-7Uqj9Fq&origin=fashilong'
  1179. if (res.errno === 0) {
  1180. let url = base + "&sid=" + id
  1181. this.setData({
  1182. id: id,
  1183. newPicUrl: res.data.brand.appListPicUrl,
  1184. sceneNum: res.data.brand.sceneNum,
  1185. canShow: res.data.brand.canShow,
  1186. contractPhone: res.data.brand.contractPhone
  1187. })
  1188. // debugger
  1189. if (this.data.many === void 0) {
  1190. this.data.many = !!res.data.brand.canShow
  1191. }
  1192. this.setData({
  1193. // peopleCount: this.data.many ? manyCount : 5,
  1194. peopleCount: manyCount
  1195. })
  1196. if (!res.data.brand.canShow) {
  1197. this.role = 'customer'
  1198. } else if (!this.options.join) {
  1199. this.role = 'leader'
  1200. }
  1201. cb(url, urlToJson(url).m, )
  1202. }
  1203. });
  1204. },
  1205. selectType(ev) {
  1206. this.getGoodsList(this.options.id, ev.target.dataset.item.category_id)
  1207. },
  1208. hideCS() {
  1209. this.setData({
  1210. showCommodity: false,
  1211. showCoupon: false,
  1212. showContact: false
  1213. })
  1214. },
  1215. hideContact() {
  1216. this.setData({
  1217. showContact: false
  1218. })
  1219. },
  1220. calcShare() {
  1221. // this.exit()
  1222. this.setData({
  1223. sendShare: false
  1224. })
  1225. },
  1226. contactKf() {
  1227. let keys = Object.keys(this.navDatas)
  1228. let goodsId = this.navDatas[keys[0]][0].id
  1229. let user = wx.getStorageSync('userinfoDetail')
  1230. util.request(api.AddTalkCount, {
  1231. goodsId,
  1232. viewId: user && user.userId || '',
  1233. sceneNum: this.data.sceneNum
  1234. }, 'get')
  1235. this.hideAlert && this.hideAlert()
  1236. this.hideContact && this.hideContact()
  1237. },
  1238. onHide() {
  1239. this.socketSendMessage('changeOnlineStatus', {
  1240. status: 0
  1241. })
  1242. this.pauseVideo = true
  1243. this.joinUrl()
  1244. }
  1245. }