123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583 |
- // pages/chat-room/chat-room.js
- const app = getApp();
- const disp = require("../../utils/broadcast.js");
- const WebIM = require("../../utils/WebIM.js")["default"];
- const util = require('../../utils/util.js');
- Page({
- /**
- * 页面的初始数据
- */
- data: {
- imgPath: app.globalData.imgPath,
- cursor: null,
- limit: 10,
- list: [],
- search_btn: true,
- search_chats: false,
- show_mask: false,
- yourname: "",
- unReadSpotNum: 0,
- unReadNoticeNum: 0,
- messageNum: 0,
- unReadTotalNotNum: 0,
- arr: [],
- show_clear: false,
- groupName: {}
- },
- /**
- * 生命周期函数--监听页面加载
- */
- onLoad: function (options) {
- // let that = this;
- // this.getRoster();
- this.listGroups();
- // this.getChatList();
- },
- /**
- * 生命周期函数--监听页面初次渲染完成
- */
- onReady: function () {
- },
- /**
- * 生命周期函数--监听页面显示
- */
- onShow: function () {
- },
- /**
- * 生命周期函数--监听页面隐藏
- */
- onHide: function () {
- },
- /**
- * 生命周期函数--监听页面卸载
- */
- onUnload: function () {
- },
- /**
- * 页面相关事件处理函数--监听用户下拉动作
- */
- onPullDownRefresh: function () {
- },
- /**
- * 页面上拉触底事件的处理函数
- */
- onReachBottom: function () {
- },
- /**
- * 跳转到群组列表
- */
- into_groups: function () {
- wx.navigateTo({
- url: "../chat-group/chat-group?myName=" + this.data.myName
- });
- },
- /**
- * 查询联系人
- */
- getRoster: function () {
- let that = this;
- let rosters = {
- success(roster) {
- console.info(roster)
- var member = [];
- for (let i = 0; i < roster.length; i++) {
- if (roster[i].subscription == "both") {
- member.push(roster[i]);
- }
- }
- wx.setStorage({
- key: "member",
- data: member
- });
- that.setData({ member: member });
- that.listGroups();
- //if(!systemReady){
- disp.fire("em.main.ready");
- //systemReady = true;
- //}
- // that.setData({
- // arr: that.getChatList(),
- // unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
- // });
- },
- error(err) {
- console.log(err);
- }
- };
- WebIM.conn.getRoster(rosters);
- },
- /**
- * 查询群组
- */
- listGroups: function () {
- var that = this;
- return WebIM.conn.getGroup({
- limit: 100,
- success: function (res) {
- console.info(res)
- let groupName = {}
- let listGroup = res.data || []
- listGroup.forEach((item) => {
- groupName[item.groupid] = item.groupname
- });
- that.setData({
- groupName
- })
- wx.setStorage({
- key: "listGroup",
- data: res.data
- });
- that.getChatList();
- },
- error: function (err) {
- console.log(err)
- }
- });
- },
- /**
- * 查询聊天记录(包含陌生人版本)
- */
- getChatList: function () {
- let myName = wx.getStorageSync("myUsername");
- let that = this
- wx.getStorageInfo({
- success: function (res) {
- // console.info(res);
- let storageKeys = res.keys;
- console.log('res.keys +++ ', res.keys);
- let newChatMsgKeys = [];
- let historyChatMsgKeys = [];
- let len = myName.length;
- storageKeys.forEach((item) => {
- // console.info(item);
- // 未读
- if (item.slice(-len) == myName && item.indexOf('rendered_') == -1) {
- newChatMsgKeys.push(item);
- }
- // 已读
- else if (item.slice(-len) == myName && item.indexOf('rendered_') > -1) {
- historyChatMsgKeys.push(item);
- }
- });
- cul.call(that, newChatMsgKeys, historyChatMsgKeys);
- }
- });
- function cul(newChatMsgKeys, historyChatMsgKeys) {
- let array = []
- let lastChatMsg;
- for (let i = 0; i < historyChatMsgKeys.length; i++) {
- // 判断新消息是否包含历史聊天(截断'rendered_')
- let index = newChatMsgKeys.indexOf(historyChatMsgKeys[i].slice(9));
- if (index > -1) {
- let newChatMsgs = wx.getStorageSync(newChatMsgKeys[index]) || [];
- // console.info('newChatMsgs', newChatMsgs);
- if (newChatMsgKeys.includes()) { }
- // 排除定位消息
- for (let k = 0; k < newChatMsgs.length; k++) {
- if (newChatMsgs[k].msg.data[0].data == 'location') {
- newChatMsgs.splice(k, 1);
- k--;
- }
- }
- if (newChatMsgs.length) {
- lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
- lastChatMsg.unReadCount = newChatMsgs.length;
- if (lastChatMsg.unReadCount > 99) {
- lastChatMsg.unReadCount = "99+";
- }
- lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
- lastChatMsg.time = that.chatTime(lastChatMsg.time);
- newChatMsgKeys.splice(index, 1);
- } else {
- let historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i]);
- // console.info('newChatMsgs', historyChatMsgs);
- // 排除定位消息
- for (let k = 0; k < historyChatMsgs.length; k++) {
- if (historyChatMsgs[k].msg.data[0].data == 'location') {
- historyChatMsgs.splice(k, 1);
- k--;
- }
- }
- if (historyChatMsgs.length) {
- lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
- lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
- lastChatMsg.time = that.chatTime(lastChatMsg.time);
- }
- }
- } else {
- let historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i]);
- // console.info('historyChatMsgs', historyChatMsgs);
- // 排除定位消息
- for (let k = 0; k < historyChatMsgs.length; k++) {
- if (historyChatMsgs[k].msg.data[0].data == 'location') {
- historyChatMsgs.splice(k, 1);
- k--;
- }
- }
- if (historyChatMsgs.length) {
- lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
- lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
- lastChatMsg.time = that.chatTime(lastChatMsg.time);
- }
- }
- if (lastChatMsg && (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom')) {
- lastChatMsg.groupName = that.data.groupName[lastChatMsg.info.to];
- }
- lastChatMsg && lastChatMsg.username != myName && array.push(lastChatMsg);
- }
- for (let i = 0; i < newChatMsgKeys.length; i++) {
- let newChatMsgs = wx.getStorageSync(newChatMsgKeys[i]) || [];
- // console.info('newChatMsgs', newChatMsgs);
- // 排除定位消息
- for (let k = 0; k < newChatMsgs.length; k++) {
- if (newChatMsgs[k].msg.data[0].data == 'location') {
- newChatMsgs.splice(k, 1);
- k--;
- }
- }
- if (newChatMsgs.length) {
- lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
- lastChatMsg.unReadCount = newChatMsgs.length;
- if (lastChatMsg.unReadCount > 99) {
- lastChatMsg.unReadCount = "99+";
- }
- lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
- lastChatMsg.time = that.chatTime(lastChatMsg.time);
- if (lastChatMsg && (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom')) {
- lastChatMsg.groupName = that.data.groupName[lastChatMsg.info.to];
- }
- lastChatMsg.username != myName && array.push(lastChatMsg)
- }
- }
- array.sort((a, b) => {
- return b.dateTimeNum - a.dateTimeNum
- });
- console.info(array)
- this.setData({
- arr: array
- });
- }
- },
- onShow: function () {
- this.getChatList()
- this.setData({
- //arr: this.getChatList(),
- unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
- messageNum: getApp().globalData.saveFriendList.length,
- unReadNoticeNum: getApp().globalData.saveGroupInvitedList.length,
- unReadTotalNotNum: getApp().globalData.saveFriendList.length + getApp().globalData.saveGroupInvitedList.length
- });
- if (getApp().globalData.isIPX) {
- this.setData({
- isIPX: true
- })
- }
- },
- openSearch: function () {
- this.setData({
- search_btn: false,
- search_chats: true,
- gotop: true
- });
- },
- onSearch: function (val) {
- var myName = wx.getStorageSync("myUsername");
- const that = this
- let searchValue = val.detail.value
- let chartList = this.data.arr;
- let serchList = [];
- console.log('arr', that.data.arr)
- chartList.forEach((item, index) => {
- if (String(item.username).indexOf(searchValue) != -1 || (item.groupName && item.groupName.indexOf(searchValue) != -1)) {
- serchList.push(item)
- }
- })
- this.setData({
- arr: serchList,
- })
- },
- cancel: function () {
- this.getChatList()
- this.setData({
- search_btn: true,
- search_chats: false,
- //arr: this.getChatList(),
- unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
- gotop: false
- });
- },
- clearInput: function () {
- this.setData({
- input_code: '',
- show_clear: false
- })
- },
- onInput: function (e) {
- let inputValue = e.detail.value
- if (inputValue) {
- this.setData({
- show_clear: true
- })
- } else {
- this.setData({
- show_clear: false
- })
- }
- },
- tab_contacts: function () {
- wx.redirectTo({
- url: "../main/main?myName=" + wx.getStorageSync("myUsername")
- });
- },
- close_mask: function () {
- this.setData({
- search_btn: true,
- search_chats: false,
- show_mask: false
- });
- },
- tab_setting: function () {
- wx.redirectTo({
- url: "../setting/setting"
- });
- },
- tab_notification: function () {
- wx.redirectTo({
- url: "../notification/notification"
- });
- },
- /**
- * 进入聊天界面
- */
- into_chatRoom: function (event) {
- let detail = event.currentTarget.dataset.item;
- console.info('detail:', detail);
- //群聊的chatType居然是singlechat?脏数据? 等sdk重写后整理一下字段
- if (detail.chatType == 'groupchat' || detail.chatType == 'chatRoom' || detail.groupName) {
- this.into_groupChatRoom(detail);
- } else {
- this.into_singleChatRoom(detail);
- }
- },
- /**
- * 进入单聊
- */
- into_singleChatRoom: function (detail) {
- var my = wx.getStorageSync("myUsername");
- let title = '';
- if (detail.info.from == my) {
- title = detail.info.toInfo.nickname;
- } else {
- title = detail.info.fromInfo.nickname;
- }
- var nameList = {
- myName: my,
- your: detail.username,
- navigationTitle: title
- };
- wx.navigateTo({
- url: "../chat-detail/chat-detail?username=" + JSON.stringify(nameList)
- });
- },
- /**
- * 进入群聊
- * 群聊 和 聊天室 (两个概念)
- */
- into_groupChatRoom: function (detail) {
- var my = wx.getStorageSync("myUsername");
- var nameList = {
- myName: my,
- your: detail.groupName,
- groupId: detail.info.to
- };
- wx.navigateTo({
- url: "../chat-group-detail/chat-group-detail?username=" + JSON.stringify(nameList)
- });
- },
- /**
- * 删除聊天
- */
- del_chat: function (event) {
- let detail = event.currentTarget.dataset.item;
- let nameList;
- let that = this;
- if (detail.chatType == 'groupchat' || detail.chatType == 'chatRoom') {
- nameList = {
- your: detail.info.to
- };
- } else {
- nameList = {
- your: detail.username
- };
- }
- var myName = wx.getStorageSync("myUsername");
- var currentPage = getCurrentPages();
- wx.showModal({
- title: "删除该聊天记录",
- confirmText: "删除",
- success: function (res) {
- if (res.confirm) {
- wx.removeStorageSync(nameList.your + myName);
- wx.removeStorageSync("rendered_" + nameList.your + myName);
- if (currentPage[0]) {
- currentPage[0].onShow();
- }
- that.getChatList()
- disp.fire("em.chat.session.remove");
- }
- },
- fail: function (err) {
- }
- });
- },
- /**
- * 进入聊天界面(废弃)
- */
- chatDetail: function (e) {
- let id = e.currentTarget.dataset.id;
- let name = e.currentTarget.dataset.name;
- wx.navigateTo({
- url: '../chat-detail/chat-detail?id=' + id + "&name=" + name,
- })
- },
- /**
- * 自定义格式化聊天时间
- * @param {*} chatTime
- */
- chatTime: function (chatTime) {
- let dateArr = chatTime.split(' ')[0].split('-');
- let timeArr = chatTime.split(' ')[1].split(':');
- let nowArr = util.formatDate(null).split(' ')[0].split('-');
- let month = dateArr[1] < 10 ? '0' + dateArr[1] : dateArr[1];
- let day = dateArr[2] < 10 ? '0' + dateArr[2] : dateArr[2];
- // console.info('dateArr', dateArr);
- // console.info('nowArr', nowArr);
- if (nowArr[0] == dateArr[0] && nowArr[1] == month && nowArr[2] == day) {
- return `${timeArr[0]}:${timeArr[1]}`;
- } else {
- return `${dateArr[0]}/${dateArr[1]}/${dateArr[2]}`;
- }
- },
- /**
- * 查询环信用户属性
- */
- getUserShowName: function (lastChatMsg) {
- util.post({
- url: '/api/easemob/getUpUserAttribute/' + lastChatMsg.username,
- success: (res) => {
- wx.hideLoading();
- console.info(res);
- return res.data.data.data.nickname;
- }
- });
- },
- /**
- * 扫一扫加入群聊
- */
- scanJoinGroup: function () {
- wx.scanCode({
- onlyFromCamera: true,
- success: (res) => {
- console.info('scanCode', res);
- if (res.path) {
- let scene = res.path.split('=')[1];
- util.get({
- url: '/api/wechat/getQrCodeParams?key=' + scene,
- success: (res) => {
- wx.hideLoading();
- console.info(res);
- if (res.data.code != 200) {
- util.toast(res.data.msg);
- } else {
- // 扫码加群
- if ('GROUP' == res.data.data.type) {
- let groupId = res.data.data.groupId;
- util.post({
- url: '/api/easemob/addGroupUser',
- data: {
- chatgroupid: groupId,
- usernames: [wx.getStorageSync('myUsername')]
- },
- success: (res) => {
- wx.hideLoading();
- console.info('addGroupUser', res);
- if (res.data.code != 200) {
- util.toast(res.data.msg);
- } else {
- let datas = res.data.data;
- if (datas && datas.error) {
- if (datas.error == 'not_found') {
- util.toast('您要加入的群聊不存在');
- } else if (datas.error == 'forbidden_op') {
- util.toast('您已经在群聊中了,请不要重复加入');
- } else {
- util.toast(datas.error);
- }
- } else {
- util.toast('群聊加入成功');
- }
- }
- }
- });
- } else {
- util.toast('请扫描群聊小程序码');
- }
- }
- }
- });
- }
- },
- fail: (err) => {
- console.info('scanCode', err);
- }
- });
- }
- })
|