UniChat 社交IM 集成环信

1.消息页

  1 //读取会话消息Vue代码
  2 function fnInitData(){
  3         vue = new Vue({
  4             el: '#vue',
  5             data: {
  6                 messages: [],
  7                 currentLocalConversationId: '',
  8                 loop: ''
  9             },
 10             beforeCreate: function() {
 11                 let that = this;
 12                 let userInfo = api.getPrefs({
 13                     key: 'userInfo',
 14                     sync: true
 15                 });
 16 
 17                 userInfo = JSON.parse(userInfo);
 18                 UIEaseChat = api.require('easeChat');
 19                 UIEaseChat.login({
 20                    username: userInfo.username,
 21                    password: window.cfg.easePassword,
 22                    autoLogin: false
 23                 },function(ret, err) {
 24                     if (ret.status || err.code == 200) {
 25                         //从本地缓存加载
 26                         fnInitDB();
 27                         fnGetConversation(userInfo.id, 0, 50, function(ret, err){
 28                           if (ret.status) {
 29                               let data = ret.data;
 30 
 31                               for(let index in data){
 32                                   if(index == 0){
 33                                       //设置当前本地缓存的最大朋友圈消息Id
 34                                       that.currentLocalConversationId = data[index].uid;
 35                                   }
 36                                   that.messages.push(JSON.parse(data[index].content));
 37                               }
 38                           }else{
 39                               console.log(JSON.stringify(err));
 40                           }
 41                         });
 42 
 43                         // 添加消息监听
 44                         UIEaseChat.addMessageListener({
 45                             name: 'receive'
 46                         }, function(ret) {
 47                             updateConversationList(ret['messages']);
 48                             //广播出去,聊天页面做数据更新
 49                             api.sendEvent({
 50                                 name: 'messageReceived',
 51                                 extra: {
 52                                     messages: ret['messages']
 53                                 }
 54                             });
 55                         });
 56 
 57                         that.syncConversation();
 58                     } else {
 59                         console.log(JSON.stringify(err));
 60                         api.alert({
 61                             msg: '网络不好,退出重试'
 62                         });
 63                     }
 64                 });
 65             },
 66             methods: {
 67                 syncConversation: function(){
 68                     let that = this;
 69                     let userInfo = api.getPrefs({
 70                         key: 'userInfo',
 71                         sync: true
 72                     });
 73 
 74                     userInfo = JSON.parse(userInfo);
 75                     UIEaseChat = api.require('easeChat');
 76 
 77                     UIEaseChat.getAllConversations(function(ret) {
 78                         let conversations = ret.conversations;
 79                         let length = conversations.length;
 80 
 81                         // 按照最新一条消息接收时间排序
 82                         for (let i = 0; i < length; i++) {
 83                             for (j = i + 1; j < length; j++) {
 84                                 if (parseInt(conversations[i]['latestMessage']['timestamp'], 10) < parseInt(conversations[j]['latestMessage']['timestamp'], 10)) {
 85                                     tmp = conversations[i];
 86                                     conversations[i] = conversations[j];
 87                                     conversations[j] = tmp;
 88                                 }
 89                             }
 90                         }
 91 
 92                         // 加载会话的头像、昵称、汇总总未读消息数量
 93                         showList(conversations);
 94                         that.messages = listData;
 95 
 96                         //保存到本地缓存
 97                         if(listData.length > 0){
 98                             fnInitDB();
 99                             fnAddConversation(userInfo.id, listData, function(ret, err){
100                               if (ret.status) {
101                                   //console.log('add Conversation success');
102                                   let latestMessageConversation = conversations[0];
103                                   that.currentLocalConversationId = latestMessageConversation.conversationId;
104                                   //console.log(that.currentLocalConversationId);
105                               }else{
106                                   console.log(JSON.stringify(err));
107                               }
108                             });
109                         }
110 
111                         // 缓存所有的聊天对象的头像
112                         window.cacheConversationsAvatar(function () {
113                             refreshAvartars();
114                         });
115                     });
116                 }
117             }
118         });
119     }
读取会话消息源码

2.通讯录

 1 function fnInitListData(callback) {
 2             let data = api.getPrefs({
 3                 key: 'friends',
 4                 sync: true
 5             });
 6             window.cacheConversationsAvatar(function(){});
 7             if (data == "") {
 8                 setTimeout(function () {
 9                     api.sendEvent({
10                         name: 'tabviewappear1'
11                     });
12                 }, 400);
13                 return;
14             }
15             data = JSON.parse(data);
16             let chat = data['chat']; // 好友
17             let groups = data['groupChat']; // 群组
18             let rooms = data['chatRoom']; // 聊天室
19             let ret = {};
20             for (let i=0; i<chat.length; i++) {
21                 let key = window.getPy(chat[i]['nickname']);
22                 if (ret.hasOwnProperty(key)) {
23                     ret[key].push({
24                         placeholderImg: 'widget://image/error-img.png',
25                         img: chat[i]['avatar'],
26                         title: chat[i]['nickname'],
27                         titleSize: 16,
28                         username: chat[i]['username'],
29                         id: chat[i]['id']
30                     });
31                 } else {
32                     ret[key] = [
33                         {
34                             placeholderImg: 'widget://image/error-img.png',
35                             img: chat[i]['avatar'],
36                             title: chat[i]['nickname'],
37                             titleSize: 16,
38                             username: chat[i]['username'],
39                             id: chat[i]['id']
40                         }
41                     ];
42                 }
43             }
44             // 排序
45             let newKey = Object.keys(ret).sort();
46             let newObj = {
47                  common: [
48                      {
49                          img: 'widget://image/icons/new-friends.png',
50                          title: '新的朋友',
51                          titleSize: 16
52                      }, {
53                          img: 'widget://image/icons/group.png',
54                          title: '群聊',
55                          titleSize: 16
56                      }
57                  ]
58             };
59             //为了把公共选项放在前面,不用重新复制数据吧
60             for (let i=0; i<newKey.length; i++) {
61                 newObj[newKey[i]] = ret[newKey[i]];
62             }
63 
64             callback(newObj);
65         }
读取通讯录信息源码

3.发现页

 1 function fnInitData(){
 2           let userInfo = window.getUserInfo();
 3 
 4           //从本地加载缓存
 5           fnInitDB();
 6           fnGetFriendsCircle(userInfo.id, 0, 1, function(ret, err) {
 7               if (ret.status) {
 8                   currentLocalMaxMessageId = ret.data[0].messageId;
 9 
10                   //此处用同步接口,加载本地未缓存的朋友圈数据
11                   window.Ajax({
12                       url: 'moments/sync',
13                       params: {
14                           currentLocalMaxMessageId: currentLocalMaxMessageId
15                       }
16                   }, function(data) {
17                       if (data.length > 0) {
18                           //反向读取朋友圈数据,插入已存在的数组
19                           let currentServerMaxMessageId = data[data.length-1].id;
20 
21                           //同步朋友圈时,新消息存入本地缓存
22                           fnAddFriendsCircles(userInfo.id, data, function(ret, err) {
23                               if (ret.status) {
24                                   currentLocalMaxMessageId = currentServerMaxMessageId;
25 
26                                   api.sendEvent({
27                                       name: 'syncFirendsCircle',
28                                       extra: {
29                                           datas: data
30                                       }
31                                   });
32                               }else{
33                                   console.log(JSON.stringify(err));
34                               }
35                           });
36                       }
37                   });
38               }else{
39                   console.log(JSON.stringify(err));
40               }
41           });
42         }
读取发现页信息源码

4.我的页

  1 function fnInitData(){
  2             vue = new Vue({
  3                 el: '#vue',
  4                 data: {
  5                     nickname: '',
  6                     username: ''
  7                 },
  8                 beforeCreate: function() {},
  9                 updated: function() {},
 10                 mounted: function() {
 11                     let userInfo = window.getUserInfo();
 12                     let nickname = userInfo.nickname;
 13                     let username = userInfo.username;
 14                     this.username = username;
 15                     this.nickname = nickname;
 16                     let avatar = userInfo.avatar;
 17                     this.localPic(avatar, 'pictor');
 18                 },
 19                 methods: {
 20                     localPic: function(url, dom) {
 21                         api.imageCache({
 22                             url: url,
 23                             policy: 'cache_only',
 24                             thumbnail: false
 25                         }, function(ret, err) {
 26                             let localPath = ret.url;
 27                             $api.attr($api.byId(dom), 'src', localPath);
 28                         });
 29                     },
 30                     changeAvatar: function (type, dom) {
 31                         window.getPicture(function(url) {
 32                             window.Ajax({
 33                                 url: 'user/changeAvatar',
 34                                 method: 'post',
 35                                 params: {
 36                                     path: url,
 37                                     type: type
 38                                 }
 39                             }, function(res) {
 40                                 vue.localPic(url, dom);
 41                                 window.refreshLogin();
 42                             });
 43                         });
 44                     },
 45                     toQrcode: function (type) {
 46                         api.openWin({
 47                             name: 'qrcode-' + type,
 48                             url: '../win.html',
 49                             pageParam: {
 50                                 title: '个人二维码',
 51                                 url: './set/qrcode.html',
 52                                 params: {
 53                                     value: type,
 54                                     text: '扫一扫加好友'
 55                                 }
 56                             }
 57                         });
 58                     },
 59                     changeName: function () {
 60                         let that = this;
 61                         api.prompt({
 62                             title: '修改昵称',
 63                             type: 'text',
 64                             buttons: ['确定', '取消']
 65                         }, function(ret, err) {
 66                             var index = ret.buttonIndex;
 67                             var text = ret.text;
 68 
 69                             if (index == 1){
 70                                 if (!text) {
 71                                     api.alert({
 72                                         title: '提示',
 73                                         msg: '不能为空',
 74                                     }, function(ret, err){});
 75                                     return;
 76                                 };
 77                                 if (text.length > 20) {
 78                                     api.alert({
 79                                         title: '提示',
 80                                         msg: '最多20个字哟',
 81                                     }, function(ret, err){});
 82                                     return;
 83                                 }
 84                                 api.showProgress({
 85                                     style: 'default',
 86                                     animationType: 'fade',
 87                                     title: '修改中...',
 88                                     text: '请稍候...',
 89                                     modal: false
 90                                 });
 91 
 92                                 // 修改昵称
 93                                 window.Ajax({
 94                                     url: 'user/changeUserInfo',
 95                                     params: {
 96                                         key: 'nickname',
 97                                         value: text
 98                                     }
 99                                 }, function (data) {
100                                     api.hideProgress();
101                                     api.toast({
102                                         msg: '修改成功',
103                                         duration: 2000,
104                                         location: 'bottom'
105                                     });
106                                     that.nickname = text;
107                                     window.refreshLogin();
108                                 });
109                             }
110                         });
111                     }
112                 }
113             });
114         }
读取我的信息源码

5.聊天页

  1 function fnInitData(){
  2             vue = new Vue({
  3                 el: '#vue',
  4                 data: {
  5                     messages: [],
  6                     isOwner: false,
  7                     owner: '',
  8                     firstLoad: true,
  9                     emotionData: [],
 10                     conversationId: api.pageParam.params.conversationId,
 11                     chatType: api.pageParam.params.chatType,
 12                     userInfo: window.getUserInfo(),
 13                     bonus: {
 14                         show: false,
 15                         name: '',
 16                         avatar: '',
 17                         msg: '',
 18                         message: '',  // 消息原始数据
 19                     },
 20                     currentLocalMaxMessageId: '',
 21                     page: 0,
 22                     pageSize: 10
 23                 },
 24                 beforeCreate: function() {
 25                     UIPhotoViewer = api.require('UIPhotoViewer');
 26                 },
 27                 updated: function() {
 28                     if (this.firstLoad) {
 29                         let that = this;
 30                         this.firstLoad = false;
 31                         setTimeout(function() {
 32                             that.scrollToBottom();
 33                         }, 100);
 34                     }
 35                 },
 36                 beforeDestroy: function () {
 37                     api.removeEventListener({
 38                         name: 'messageReceived'
 39                     });
 40                 },
 41                 mounted: function() {
 42                     //监听新消息事件
 43                     let that = this;
 44 
 45                     //获取最近的聊天记录
 46                     that.syncServiceMessageToLocal();
 47 
 48                     //收到消息后响应方法
 49                     api.addEventListener({
 50                         name: 'messageReceived'
 51                     }, function(ret, err) {
 52                         let msgs = ret.value.messages;
 53                         let flag = false;
 54                         for (let i = 0; i < msgs.length; i++) {
 55                             if (msgs[i].conversationId == api.pageParam.params.conversationId) {
 56                                 flag = true;
 57                                 msgs[i]['showHeader'] = true;
 58                                 if (that.messages.length &&
 59                                     msgs[i].timestamp - that.messages[that.messages.length - 1]. timestamp < 5 * 60 * 1000) {
 60                                         msgs[i]['showHeader'] = false;
 61                                     }
 62                                 that.messages.push(msgs[i]);
 63                                 setTimeout(function() {
 64                                     //滚动聊天区域到底部
 65                                     that.scrollToBottom();
 66                                 }, 100);
 67 
 68                                 // 如果不是语音且不是红包,则标记已读
 69                                 if (msgs[i].body.type != 'voice' && !that.isBonus(msgs[i])) {
 70                                     // 标记已读
 71                                     UIEaseChat.markMessageAsRead({
 72                                         conversationId: api.pageParam.params.conversationId,
 73                                         type: api.pageParam.params.chatType,
 74                                         messageId: msgs[i]['messageId']
 75                                     },function(ret,err) {});
 76                                 }
 77 
 78                             }
 79                         }
 80                         // 更新主页的数据
 81                         if (flag) {
 82                             api.sendEvent({
 83                                 name: 'messageReaded',
 84                                 extra: {
 85                                     conversationId: api.pageParam.params.conversationId
 86                                 }
 87                             });
 88                         }
 89                     });
 90 
 91                     //注释原因:不使用UIeaseChat输入框,不需要初始化底部的输入框
 92                     //that.initChatBox();
 93 
 94                     //注释原因:不使用UIeaseChat输入框,获取emotion的所有路径
 95                     //that.initEmotionData();
 96                 },
 97                 methods: {
 98                     loadMessageFromLocal: function() {
 99                       let that = this;
100                       let userInfo = window.getUserInfo();
101 
102                       that.page = that.page + 1;
103 
104                       fnGetFriendsChat(userInfo.id,
105                         api.pageParam.params.conversationId,
106                         that.currentLocalMaxMessageId,
107                         that.page,
108                         that.pageSize,
109                         function(ret, err){
110                             if (ret.status) {
111                               let data = ret.data;
112                               // console.log(that.currentLocalMaxMessageId);
113                               // console.log(JSON.stringify(data));
114                               for(let index in data){
115                                   //console.log('data array index:'+index);
116                                   if(index == 0){
117                                       //设置当前本地缓存的最大朋友圈消息Id
118                                       that.currentLocalMaxMessageId = data[index].messageId;
119                                   }
120 
121                                   vue.messages.splice(0, 0, JSON.parse(data[index].content));
122                               }
123 
124                               mescroll.endSuccess();
125                             }else{
126                                 console.log(JSON.stringify(err));
127                             }
128                       });
129                     },
130                     syncServiceMessageToLocal: function() {
131                         let that = this;
132 
133                         UIEaseChat = api.require('easeChat');
134                         UIEaseChat.loadMessageFromDB({
135                             conversationId: api.pageParam.params.conversationId,
136                             type: api.pageParam.params.chatType,
137                             pagesize: that.pageSize
138                           }, function(ret) {
139                             if(ret.messages.length > 0){
140                               //存在未缓存的消息
141                                 let messages = ret.messages;
142                                 let lastIndex = 0;
143                                 for (let i=0; i<messages.length; i++) {
144                                     if (i == 0) {
145                                         messages[i]['showHeader'] = true;
146                                         that.currentLocalMaxMessageId =  messages[i]['messageId'];
147                                     }
148                                     let pre = i - 1 >= 0 ? i - 1 : 0;
149                                     if (i == messages.lenght - 1 && messages[i].timestamp - messages[pre].timestamp > 5 * 60 * 1000) {
150                                         messages[i]['showHeader'] = true;
151                                     }
152                                     if (messages[i].timestamp - messages[lastIndex].timestamp > 30 * 60 * 1000) {
153                                         messages[i]['showHeader'] = true;
154                                         lastIndex = i;
155                                     }
156 
157                                     // 如果不是语音且不是红包,则标记已读
158                                     if (messages[i].body.type != 'voice' && !that.isBonus(messages[i])) {
159                                         if (!messages[i].isRead) {
160                                             // 标记已读
161                                             UIEaseChat.markMessageAsRead({
162                                                 conversationId: api.pageParam.params.conversationId,
163                                                 type: api.pageParam.params.chatType,
164                                                 messageId: messages[i]['messageId']
165                                             },function(ret,err) {});
166                                         }
167                                     }
168 
169                                 }
170 
171                                 that.messages = messages;
172 
173                                 // console.log(JSON.stringify(messages));
174 
175                                 //当前新消息时,同步消息到本地
176                                 // if(messages.length > 0){
177                                 //   let userInfo = window.getUserInfo();
178                                 //   fnAddFriendsChat(userInfo.id,api.pageParam.params.conversationId,messages,
179                                 //     function(ret, err){
180                                 //         if(ret.status){
181                                 //           console.log('add message success');
182                                 //         }else{
183                                 //           console.log(JSON.stringify(err));
184                                 //         }
185                                 //   });
186                                 // }
187                             }
188                         });
189                     }
190             });
191         }
读取聊天信息源码

6.朋友圈页

 1 function fnInitData(){
 2           vue = new Vue({
 3               el: '#vue',
 4               data: {
 5                   datas: [],
 6                   page: 0,
 7                   pageSize: 10,
 8                   currentLocalMaxMessageId: 0
 9               },
10               beforeCreate: function() {},
11               updated: function() {},
12               mounted: function() {
13                   let userInfo = window.getUserInfo();
14                   let topBack = userInfo.pyqImg;
15                   let avatar = userInfo.avatar;
16                   this.localPic(avatar, 'avatar');
17                   this.localPic(topBack, 'cover');
18 
19                   //从本地缓存加载一页数据
20                   // if(this.currentLocalMaxMessageId == 0){
21                   //   this.photoSync();
22                   // }else{
23                     this.photoShow();
24                   // }
25               },
26               methods: {
27                   localPic: function(url, dom) {
28                       // 缓存图片
29                       api.imageCache({
30                           url: url,
31                           policy: 'cache_only',
32                           thumbnail: false
33                       }, function(ret, err) {
34                           let localPath = ret.url;
35                           $api.attr($api.byId(dom), 'src', localPath);
36                       });
37                   },
38                   photoSync: function() {
39                       // 与服务器同步朋友圈 下拉操作
40                       let that = this;
41 
42                       //此处用同步接口,加载本地未缓存的朋友圈数据
43                       window.Ajax({
44                           url: 'moments/sync',
45                           params: {
46                               currentLocalMaxMessageId: that.currentLocalMaxMessageId
47                           }
48                       }, function(data) {
49                           let currentServerMaxMessageId = '';
50 
51                           if (data.length > 0) {
52                               //反向读取朋友圈数据,插入已存在的数组
53                               for (var i = data.length-1; i >= 0; i--){
54                                   that.datas.splice(0, 0, data[i]);
55 
56                                   if(i == 0){
57                                       currentServerMaxMessageId = data[i].id;
58                                   }
59                               }
60 
61                               //同步朋友圈时,新消息存入本地缓存
62                               let userInfo = window.getUserInfo();
63                               fnAddFriendsCircles(userInfo.id, data, function(ret, err) {
64                                   if (ret.status) {
65                                       // console.log('add success');
66 
67                                       that.currentLocalMaxMessageId = currentServerMaxMessageId;
68                                   }else{
69                                       console.log(JSON.stringify(err));
70                                   }
71                               });
72 
73                               //从本地加载缓存
74                               // fnGetFriendsCircle(userInfo.id, 1, 2, function(ret, err) {
75                               //     if (ret.status) {
76                               //         console.log(JSON.stringify(ret));
77                               //     }else{
78                               //         console.log(JSON.stringify(err));
79                               //     }
80                               // });
81                           }
82 
83                           mescroll.endSuccess();
84                       });
85                   }
86               }
87           });
88         }
读取朋友圈信息源码
原文地址:https://www.cnblogs.com/jerryqm/p/11428398.html