chat-room.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. // pages/chat-room/chat-room.js
  2. const app = getApp();
  3. const disp = require("../../utils/broadcast.js");
  4. const WebIM = require("../../utils/WebIM.js")["default"];
  5. const util = require('../../utils/util.js');
  6. Page({
  7. /**
  8. * 页面的初始数据
  9. */
  10. data: {
  11. imgPath: app.globalData.imgPath,
  12. cursor: null,
  13. limit: 10,
  14. list: [],
  15. search_btn: true,
  16. search_chats: false,
  17. show_mask: false,
  18. yourname: "",
  19. unReadSpotNum: 0,
  20. unReadNoticeNum: 0,
  21. messageNum: 0,
  22. unReadTotalNotNum: 0,
  23. arr: [],
  24. show_clear: false,
  25. groupName: {}
  26. },
  27. /**
  28. * 生命周期函数--监听页面加载
  29. */
  30. onLoad: function (options) {
  31. // let that = this;
  32. // this.getRoster();
  33. this.listGroups();
  34. // this.getChatList();
  35. },
  36. /**
  37. * 生命周期函数--监听页面初次渲染完成
  38. */
  39. onReady: function () {
  40. },
  41. /**
  42. * 生命周期函数--监听页面显示
  43. */
  44. onShow: function () {
  45. },
  46. /**
  47. * 生命周期函数--监听页面隐藏
  48. */
  49. onHide: function () {
  50. },
  51. /**
  52. * 生命周期函数--监听页面卸载
  53. */
  54. onUnload: function () {
  55. },
  56. /**
  57. * 页面相关事件处理函数--监听用户下拉动作
  58. */
  59. onPullDownRefresh: function () {
  60. },
  61. /**
  62. * 页面上拉触底事件的处理函数
  63. */
  64. onReachBottom: function () {
  65. },
  66. /**
  67. * 跳转到群组列表
  68. */
  69. into_groups: function () {
  70. wx.navigateTo({
  71. url: "../chat-group/chat-group?myName=" + this.data.myName
  72. });
  73. },
  74. /**
  75. * 查询联系人
  76. */
  77. getRoster: function () {
  78. let that = this;
  79. let rosters = {
  80. success(roster) {
  81. console.info(roster)
  82. var member = [];
  83. for (let i = 0; i < roster.length; i++) {
  84. if (roster[i].subscription == "both") {
  85. member.push(roster[i]);
  86. }
  87. }
  88. wx.setStorage({
  89. key: "member",
  90. data: member
  91. });
  92. that.setData({ member: member });
  93. that.listGroups();
  94. //if(!systemReady){
  95. disp.fire("em.main.ready");
  96. //systemReady = true;
  97. //}
  98. // that.setData({
  99. // arr: that.getChatList(),
  100. // unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
  101. // });
  102. },
  103. error(err) {
  104. console.log(err);
  105. }
  106. };
  107. WebIM.conn.getRoster(rosters);
  108. },
  109. /**
  110. * 查询群组
  111. */
  112. listGroups: function () {
  113. var that = this;
  114. return WebIM.conn.getGroup({
  115. limit: 100,
  116. success: function (res) {
  117. console.info(res)
  118. let groupName = {}
  119. let listGroup = res.data || []
  120. listGroup.forEach((item) => {
  121. groupName[item.groupid] = item.groupname
  122. });
  123. that.setData({
  124. groupName
  125. })
  126. wx.setStorage({
  127. key: "listGroup",
  128. data: res.data
  129. });
  130. that.getChatList();
  131. },
  132. error: function (err) {
  133. console.log(err)
  134. }
  135. });
  136. },
  137. /**
  138. * 查询聊天记录(包含陌生人版本)
  139. */
  140. getChatList: function () {
  141. let myName = wx.getStorageSync("myUsername");
  142. let that = this
  143. wx.getStorageInfo({
  144. success: function (res) {
  145. // console.info(res);
  146. let storageKeys = res.keys;
  147. console.log('res.keys +++ ', res.keys);
  148. let newChatMsgKeys = [];
  149. let historyChatMsgKeys = [];
  150. let len = myName.length;
  151. storageKeys.forEach((item) => {
  152. // console.info(item);
  153. // 未读
  154. if (item.slice(-len) == myName && item.indexOf('rendered_') == -1) {
  155. newChatMsgKeys.push(item);
  156. }
  157. // 已读
  158. else if (item.slice(-len) == myName && item.indexOf('rendered_') > -1) {
  159. historyChatMsgKeys.push(item);
  160. }
  161. });
  162. cul.call(that, newChatMsgKeys, historyChatMsgKeys);
  163. }
  164. });
  165. function cul(newChatMsgKeys, historyChatMsgKeys) {
  166. let array = []
  167. let lastChatMsg;
  168. for (let i = 0; i < historyChatMsgKeys.length; i++) {
  169. // 判断新消息是否包含历史聊天(截断'rendered_')
  170. let index = newChatMsgKeys.indexOf(historyChatMsgKeys[i].slice(9));
  171. if (index > -1) {
  172. let newChatMsgs = wx.getStorageSync(newChatMsgKeys[index]) || [];
  173. // console.info('newChatMsgs', newChatMsgs);
  174. if (newChatMsgKeys.includes()) { }
  175. // 排除定位消息
  176. for (let k = 0; k < newChatMsgs.length; k++) {
  177. if (newChatMsgs[k].msg.data[0].data == 'location') {
  178. newChatMsgs.splice(k, 1);
  179. k--;
  180. }
  181. }
  182. if (newChatMsgs.length) {
  183. lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
  184. lastChatMsg.unReadCount = newChatMsgs.length;
  185. if (lastChatMsg.unReadCount > 99) {
  186. lastChatMsg.unReadCount = "99+";
  187. }
  188. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  189. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  190. newChatMsgKeys.splice(index, 1);
  191. } else {
  192. let historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i]);
  193. // console.info('newChatMsgs', historyChatMsgs);
  194. // 排除定位消息
  195. for (let k = 0; k < historyChatMsgs.length; k++) {
  196. if (historyChatMsgs[k].msg.data[0].data == 'location') {
  197. historyChatMsgs.splice(k, 1);
  198. k--;
  199. }
  200. }
  201. if (historyChatMsgs.length) {
  202. lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
  203. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  204. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  205. }
  206. }
  207. } else {
  208. let historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i]);
  209. // console.info('historyChatMsgs', historyChatMsgs);
  210. // 排除定位消息
  211. for (let k = 0; k < historyChatMsgs.length; k++) {
  212. if (historyChatMsgs[k].msg.data[0].data == 'location') {
  213. historyChatMsgs.splice(k, 1);
  214. k--;
  215. }
  216. }
  217. if (historyChatMsgs.length) {
  218. lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
  219. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  220. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  221. }
  222. }
  223. if (lastChatMsg && (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom')) {
  224. lastChatMsg.groupName = that.data.groupName[lastChatMsg.info.to];
  225. }
  226. lastChatMsg && lastChatMsg.username != myName && array.push(lastChatMsg);
  227. }
  228. for (let i = 0; i < newChatMsgKeys.length; i++) {
  229. let newChatMsgs = wx.getStorageSync(newChatMsgKeys[i]) || [];
  230. // console.info('newChatMsgs', newChatMsgs);
  231. // 排除定位消息
  232. for (let k = 0; k < newChatMsgs.length; k++) {
  233. if (newChatMsgs[k].msg.data[0].data == 'location') {
  234. newChatMsgs.splice(k, 1);
  235. k--;
  236. }
  237. }
  238. if (newChatMsgs.length) {
  239. lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
  240. lastChatMsg.unReadCount = newChatMsgs.length;
  241. if (lastChatMsg.unReadCount > 99) {
  242. lastChatMsg.unReadCount = "99+";
  243. }
  244. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  245. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  246. if (lastChatMsg && (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom')) {
  247. lastChatMsg.groupName = that.data.groupName[lastChatMsg.info.to];
  248. }
  249. lastChatMsg.username != myName && array.push(lastChatMsg)
  250. }
  251. }
  252. array.sort((a, b) => {
  253. return b.dateTimeNum - a.dateTimeNum
  254. });
  255. console.info(array)
  256. this.setData({
  257. arr: array
  258. });
  259. }
  260. },
  261. onShow: function () {
  262. this.getChatList()
  263. this.setData({
  264. //arr: this.getChatList(),
  265. unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
  266. messageNum: getApp().globalData.saveFriendList.length,
  267. unReadNoticeNum: getApp().globalData.saveGroupInvitedList.length,
  268. unReadTotalNotNum: getApp().globalData.saveFriendList.length + getApp().globalData.saveGroupInvitedList.length
  269. });
  270. if (getApp().globalData.isIPX) {
  271. this.setData({
  272. isIPX: true
  273. })
  274. }
  275. },
  276. openSearch: function () {
  277. this.setData({
  278. search_btn: false,
  279. search_chats: true,
  280. gotop: true
  281. });
  282. },
  283. onSearch: function (val) {
  284. var myName = wx.getStorageSync("myUsername");
  285. const that = this
  286. let searchValue = val.detail.value
  287. let chartList = this.data.arr;
  288. let serchList = [];
  289. console.log('arr', that.data.arr)
  290. chartList.forEach((item, index) => {
  291. if (String(item.username).indexOf(searchValue) != -1 || (item.groupName && item.groupName.indexOf(searchValue) != -1)) {
  292. serchList.push(item)
  293. }
  294. })
  295. this.setData({
  296. arr: serchList,
  297. })
  298. },
  299. cancel: function () {
  300. this.getChatList()
  301. this.setData({
  302. search_btn: true,
  303. search_chats: false,
  304. //arr: this.getChatList(),
  305. unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
  306. gotop: false
  307. });
  308. },
  309. clearInput: function () {
  310. this.setData({
  311. input_code: '',
  312. show_clear: false
  313. })
  314. },
  315. onInput: function (e) {
  316. let inputValue = e.detail.value
  317. if (inputValue) {
  318. this.setData({
  319. show_clear: true
  320. })
  321. } else {
  322. this.setData({
  323. show_clear: false
  324. })
  325. }
  326. },
  327. tab_contacts: function () {
  328. wx.redirectTo({
  329. url: "../main/main?myName=" + wx.getStorageSync("myUsername")
  330. });
  331. },
  332. close_mask: function () {
  333. this.setData({
  334. search_btn: true,
  335. search_chats: false,
  336. show_mask: false
  337. });
  338. },
  339. tab_setting: function () {
  340. wx.redirectTo({
  341. url: "../setting/setting"
  342. });
  343. },
  344. tab_notification: function () {
  345. wx.redirectTo({
  346. url: "../notification/notification"
  347. });
  348. },
  349. /**
  350. * 进入聊天界面
  351. */
  352. into_chatRoom: function (event) {
  353. let detail = event.currentTarget.dataset.item;
  354. console.info('detail:', detail);
  355. //群聊的chatType居然是singlechat?脏数据? 等sdk重写后整理一下字段
  356. if (detail.chatType == 'groupchat' || detail.chatType == 'chatRoom' || detail.groupName) {
  357. this.into_groupChatRoom(detail);
  358. } else {
  359. this.into_singleChatRoom(detail);
  360. }
  361. },
  362. /**
  363. * 进入单聊
  364. */
  365. into_singleChatRoom: function (detail) {
  366. var my = wx.getStorageSync("myUsername");
  367. let title = '';
  368. if (detail.info.from == my) {
  369. title = detail.info.toInfo.nickname;
  370. } else {
  371. title = detail.info.fromInfo.nickname;
  372. }
  373. var nameList = {
  374. myName: my,
  375. your: detail.username,
  376. navigationTitle: title
  377. };
  378. wx.navigateTo({
  379. url: "../chat-detail/chat-detail?username=" + JSON.stringify(nameList)
  380. });
  381. },
  382. /**
  383. * 进入群聊
  384. * 群聊 和 聊天室 (两个概念)
  385. */
  386. into_groupChatRoom: function (detail) {
  387. var my = wx.getStorageSync("myUsername");
  388. var nameList = {
  389. myName: my,
  390. your: detail.groupName,
  391. groupId: detail.info.to
  392. };
  393. wx.navigateTo({
  394. url: "../chat-group-detail/chat-group-detail?username=" + JSON.stringify(nameList)
  395. });
  396. },
  397. /**
  398. * 删除聊天
  399. */
  400. del_chat: function (event) {
  401. let detail = event.currentTarget.dataset.item;
  402. let nameList;
  403. let that = this;
  404. if (detail.chatType == 'groupchat' || detail.chatType == 'chatRoom') {
  405. nameList = {
  406. your: detail.info.to
  407. };
  408. } else {
  409. nameList = {
  410. your: detail.username
  411. };
  412. }
  413. var myName = wx.getStorageSync("myUsername");
  414. var currentPage = getCurrentPages();
  415. wx.showModal({
  416. title: "删除该聊天记录",
  417. confirmText: "删除",
  418. success: function (res) {
  419. if (res.confirm) {
  420. wx.removeStorageSync(nameList.your + myName);
  421. wx.removeStorageSync("rendered_" + nameList.your + myName);
  422. if (currentPage[0]) {
  423. currentPage[0].onShow();
  424. }
  425. that.getChatList()
  426. disp.fire("em.chat.session.remove");
  427. }
  428. },
  429. fail: function (err) {
  430. }
  431. });
  432. },
  433. /**
  434. * 进入聊天界面(废弃)
  435. */
  436. chatDetail: function (e) {
  437. let id = e.currentTarget.dataset.id;
  438. let name = e.currentTarget.dataset.name;
  439. wx.navigateTo({
  440. url: '../chat-detail/chat-detail?id=' + id + "&name=" + name,
  441. })
  442. },
  443. /**
  444. * 自定义格式化聊天时间
  445. * @param {*} chatTime
  446. */
  447. chatTime: function (chatTime) {
  448. let dateArr = chatTime.split(' ')[0].split('-');
  449. let timeArr = chatTime.split(' ')[1].split(':');
  450. let nowArr = util.formatDate(null).split(' ')[0].split('-');
  451. let month = dateArr[1] < 10 ? '0' + dateArr[1] : dateArr[1];
  452. let day = dateArr[2] < 10 ? '0' + dateArr[2] : dateArr[2];
  453. // console.info('dateArr', dateArr);
  454. // console.info('nowArr', nowArr);
  455. if (nowArr[0] == dateArr[0] && nowArr[1] == month && nowArr[2] == day) {
  456. return `${timeArr[0]}:${timeArr[1]}`;
  457. } else {
  458. return `${dateArr[0]}/${dateArr[1]}/${dateArr[2]}`;
  459. }
  460. },
  461. /**
  462. * 查询环信用户属性
  463. */
  464. getUserShowName: function (lastChatMsg) {
  465. util.post({
  466. url: '/api/easemob/getUpUserAttribute/' + lastChatMsg.username,
  467. success: (res) => {
  468. wx.hideLoading();
  469. console.info(res);
  470. return res.data.data.data.nickname;
  471. }
  472. });
  473. },
  474. /**
  475. * 扫一扫加入群聊
  476. */
  477. scanJoinGroup: function () {
  478. wx.scanCode({
  479. onlyFromCamera: true,
  480. success: (res) => {
  481. console.info('scanCode', res);
  482. if (res.path) {
  483. let scene = res.path.split('=')[1];
  484. util.get({
  485. url: '/api/wechat/getQrCodeParams?key=' + scene,
  486. success: (res) => {
  487. wx.hideLoading();
  488. console.info(res);
  489. if (res.data.code != 200) {
  490. util.toast(res.data.msg);
  491. } else {
  492. // 扫码加群
  493. if ('GROUP' == res.data.data.type) {
  494. let groupId = res.data.data.groupId;
  495. util.post({
  496. url: '/api/easemob/addGroupUser',
  497. data: {
  498. chatgroupid: groupId,
  499. usernames: [wx.getStorageSync('myUsername')]
  500. },
  501. success: (res) => {
  502. wx.hideLoading();
  503. console.info('addGroupUser', res);
  504. if (res.data.code != 200) {
  505. util.toast(res.data.msg);
  506. } else {
  507. let datas = res.data.data;
  508. if (datas && datas.error) {
  509. if (datas.error == 'not_found') {
  510. util.toast('您要加入的群聊不存在');
  511. } else if (datas.error == 'forbidden_op') {
  512. util.toast('您已经在群聊中了,请不要重复加入');
  513. } else {
  514. util.toast(datas.error);
  515. }
  516. } else {
  517. util.toast('群聊加入成功');
  518. }
  519. }
  520. }
  521. });
  522. } else {
  523. util.toast('请扫描群聊小程序码');
  524. }
  525. }
  526. }
  527. });
  528. }
  529. },
  530. fail: (err) => {
  531. console.info('scanCode', err);
  532. }
  533. });
  534. }
  535. })