socket.js 35 KB

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