123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706 |
- <script>
- let WebIM = (wx.WebIM = require("./utils/WebIM")["default"]);
- let msgStorage = require("./components/chat/msgstorage");
- let msgType = require("./components/chat/msgtype");
- let disp = require("./utils/broadcast");
- let logout = false;
- function ack(receiveMsg) {
- // 处理未读消息回执
- var bodyId = receiveMsg.id; // 需要发送已读回执的消息id
-
- var ackMsg = new WebIM.message("read", WebIM.conn.getUniqueId());
- ackMsg.set({
- id: bodyId,
- to: receiveMsg.from,
- });
- WebIM.conn.send(ackMsg.body);
- }
- function onMessageError(err) {
- if (err.type === "error") {
- uni.showToast({
- title: err.errorText,
- });
- return false;
- }
-
- return true;
- }
- function getCurrentRoute() {
- let pages = getCurrentPages();
- if (pages.length > 0) {
- let currentPage = pages[pages.length - 1];
- return currentPage.route;
- }
- return "/";
- }
-
-
- // 包含陌生人版本
- function calcUnReadSpot(message) {
- let myName = uni.getStorageSync("myUsername");
- uni.getStorageInfo({
- success: function (res) {
- let storageKeys = res.keys;
- let newChatMsgKeys = [];
- let historyChatMsgKeys = [];
- storageKeys.forEach((item) => {
- if (item.indexOf(myName) > -1 && item.indexOf("rendered_") == -1) {
- newChatMsgKeys.push(item);
- }
- });
- let count = newChatMsgKeys.reduce(function (result, curMember, idx) {
- let chatMsgs;
- chatMsgs = uni.getStorageSync(curMember) || [];
- return result + chatMsgs.length;
- }, 0);
-
- getApp().globalData.unReadMessageNum = count;
- disp.fire("em.unreadspot", message);
- },
- });
- }
-
- function saveGroups() {
- var me = this;
- return WebIM.conn.getGroup({
- limit: 50,
- success: function (res) {
- uni.setStorage({
- key: "listGroup",
- data: res.data,
- });
- },
- error: function (err) {
- console.log(err);
- },
- });
- }
- import amap from '@/static/js/amap-wx.130.js'
- var amapPlugin = new amap.AMapWX({
- key: 'bb69713f3c3d3c85e2662d313daa47b9'
- });
- import webIM from './utils/WebIM.js'
- var that = ''
- export default {
- globalData: {
- unReadMessageNum: 0,
- userInfo: null,
- saveFriendList: [],
- saveGroupInvitedList: [],
- isIPX: false, //是否为iphone X
- conn: {
- closed: false,
- curOpenOpt: {},
-
- open(opt) {
- uni.showLoading({
- title: "正在初始化客户端..",
- mask: true,
- });
- this.curOpenOpt = opt;
- WebIM.conn.open(opt);
- this.closed = false;
- },
-
- reopen() {
- if (this.closed) {
- //this.open(this.curOpenOpt);
- WebIM.conn.open(this.curOpenOpt);
- this.closed = false;
- }
- },
- },
- onLoginSuccess: function(myName) {
- uni.hideLoading();
- uni.redirectTo({
- url: "../chat/chat?myName=" + myName,
- });
- },
-
- getUserInfo(cb) {
- var me = this;
-
- if (this.userInfo) {
- typeof cb == "function" && cb(this.userInfo);
- } else {
- // 调用登录接口
- uni.login({
- success() {
- uni.getUserInfo({
- success(res) {
- me.userInfo = res.userInfo;
- typeof cb == "function" && cb(me.userInfo);
- },
- });
- },
- });
- }
- },
-
- checkIsIPhoneX: function() {
- const me = this;
- uni.getSystemInfo({
- success: function(res) {
- // 根据 model 进行判断
- if (res.model && res.model.search("iPhone X") != -1) {
- me.isIPX = true;
- }
- },
- });
- },
- getLoca: function() {
- var city = uni.getStorageSync('city')
- return new Promise((resolve, reject) => {
- if(!city) {
- uni.authorize({
- scope: 'scope.userLocation',
- success() {
- uni.getLocation({
- type: 'wgs84',
- success(res) {
- amapPlugin.getRegeo({
- success(data) {
- console.log('获取当前所在位置',data[0].regeocodeData.addressComponent);
- uni.setStorageSync("location",data[0].regeocodeData.addressComponent)
- resolve(data)
- },
- fail(err) {
- console.log('err=',err)
- }
- })
- },
- fail(err){
- console.log('err=',err)
- }
- })
- },
- fail(err) {
- console.log('error',err)
- uni.showModal({
- title: '提示',
- content: '需要获取用户位置信息权限',
- confirmText: '前往设置',
- confirmColor: '#3CC51F',
- success(res) {
- if (res.confirm) {
- uni.openSetting(); // 打开小程序设置页面,可以让用户开启需要的权限
-
- }
- }
- })
- }
- })
- }
- })
-
- }
- },
- onLoad() {
- that = this
- },
- onLaunch: function() {
- console.log('App Launch')
- this.HXlogin()
- var me = this;
- var logs = uni.getStorageSync("logs") || [];
- logs.unshift(Date.now());
- uni.setStorageSync("logs", logs); //
-
- disp.on("em.main.ready", function() {
- calcUnReadSpot();
- });
- disp.on("em.chatroom.leave", function() {
- calcUnReadSpot();
- });
- disp.on("em.chat.session.remove", function() {
- calcUnReadSpot();
- });
- disp.on("em.chat.audio.fileLoaded", function() {
- calcUnReadSpot();
- });
- disp.on("em.main.deleteFriend", function() {
- calcUnReadSpot();
- });
- disp.on("em.chat.audio.fileLoaded", function() {
- calcUnReadSpot();
- }); //
-
- WebIM.conn.listen({
- onOpened(message) {
- console.log('>>>>>>环信登录成功啦')
- },
-
- onReconnect() {
- /* uni.showToast({
- title: "重连中...",
- duration: 2000,
- }); */
- },
-
- onSocketConnected() {
- /* uni.showToast({
- title: "socket连接成功",
- duration: 2000,
- }); */
- },
-
- onClosed() {
- /* uni.showToast({
- title: "网络已断开",
- icon: "none",
- duration: 2000,
- }); */
- uni.redirectTo({
- url: "/pages/login/codeLogin/codeLogin",
- });
- me.globalData.conn.closed = true;
- WebIM.conn.close();
- },
-
- onInviteMessage(message) {
- me.globalData.saveGroupInvitedList.push(message);
- disp.fire("em.invite.joingroup", message); // uni.showModal({
- // title: message.from + " 已邀你入群 " + message.roomid,
- // success(){
- // disp.fire("em.invite.joingroup", message);
- // },
- // error(){
- // disp.fire("em.invite.joingroup", message);
- // }
- // });
- },
-
- onReadMessage(message) {
- //console.log('已读', message)
- },
-
- //onPresence为旧版 ,建议参考最新增删好友api文档 :http://docs-im.easemob.com/im/web/basics/buddy
- onPresence(message) {
-
- switch (message.type) {
- case "unsubscribe":
- break;
- // 好友邀请列表
- case "subscribe":
- for (let i = 0; i < me.globalData.saveFriendList.length; i++) {
- if (me.globalData.saveFriendList[i].from === message.from) {
- me.globalData.saveFriendList[i] = message;
- disp.fire("em.subscribe");
- return;
- }
- }
- msgStorage.saveReceiveMsg(message, 'INFORM'); //存添加好友消息,方便展示通知
- me.globalData.saveFriendList.push(message);
- disp.fire("em.subscribe");
-
- break;
-
- case "subscribed":
- /* uni.showToast({
- title: "添加成功",
- duration: 1000,
- }); */
- disp.fire("em.subscribed");
- break;
-
- case "unsubscribed":
- disp.fire("em.unsubscribed");
- break;
- case "direct_joined":
- saveGroups();
- /* uni.showToast({
- title: "已进群",
- duration: 1000,
- }); */
- break;
- case "memberJoinPublicGroupSuccess":
- saveGroups();
- /* uni.showToast({
- title: "已进群",
- duration: 1000,
- }); */
- break;
- case "invite":
- // 防止重复添加
- for (let i = 0; i < me.globalData.saveGroupInvitedList.length; i++) {
- if (me.globalData.saveGroupInvitedList[i].from === message.from) {
- me.globalData.saveGroupInvitedList[i] = message;
- disp.fire("em.invite.joingroup")
- return;
- }
- }
- me.globalData.saveGroupInvitedList.push(message);
- disp.fire("em.invite.joingroup");
- msgStorage.saveReceiveMsg(message, 'INFORM'); //存添加好友消息,方便展示通知
- break;
- case "unavailable":
- disp.fire("em.contacts.remove");
- disp.fire("em.group.leaveGroup", message);
- break;
-
- case "deleteGroupChat":
- disp.fire("em.invite.deleteGroup", message);
- break;
-
- case "leaveGroup":
- disp.fire("em.group.leaveGroup", message);
- break;
-
- case "removedFromGroup":
- disp.fire("em.group.leaveGroup", message);
- break;
-
- default:
- break;
- }
- },
-
- onRoster(message) {
- // let pages = getCurrentPages();
- // if(pages[0]){
- // pages[0].onShow();
- // }
- },
-
- onVideoMessage(message) {
- console.log("onVideoMessage: ", message);
-
- if (message) {
- msgStorage.saveReceiveMsg(message, msgType.VIDEO);
- }
-
- calcUnReadSpot(message);
- ack(message);
- },
-
- onAudioMessage(message) {
- console.log("onAudioMessage", message);
-
- if (message) {
- if (onMessageError(message)) {
- msgStorage.saveReceiveMsg(message, msgType.AUDIO);
- }
-
- calcUnReadSpot(message);
- ack(message);
- }
- },
-
- onCmdMessage(message) {
- console.log("onCmdMessage", message);
-
- if (message) {
- if (onMessageError(message)) {
- msgStorage.saveReceiveMsg(message, msgType.CMD);
- }
-
- calcUnReadSpot(message);
- ack(message);
- }
- },
-
- // onLocationMessage(message){
- // console.log("Location message: ", message);
- // if(message){
- // msgStorage.saveReceiveMsg(message, msgType.LOCATION);
- // }
- // },
- onTextMessage(message) {
- console.log("onTextMessage", message);
-
- if (message) {
- if (onMessageError(message)) {
- msgStorage.saveReceiveMsg(message, msgType.TEXT);
- }
-
- calcUnReadSpot(message);
- ack(message);
- }
- },
-
- onEmojiMessage(message) {
- console.log("onEmojiMessage", message);
-
- if (message) {
- if (onMessageError(message)) {
- msgStorage.saveReceiveMsg(message, msgType.EMOJI);
- }
-
- calcUnReadSpot(message);
- ack(message);
- }
- },
-
- onPictureMessage(message) {
- console.log("onPictureMessage", message);
-
- if (message) {
- if (onMessageError(message)) {
- msgStorage.saveReceiveMsg(message, msgType.IMAGE);
- }
-
- calcUnReadSpot(message);
- ack(message);
- }
- },
-
- onFileMessage(message) {
- console.log("onFileMessage", message);
-
- if (message) {
- if (onMessageError(message)) {
- msgStorage.saveReceiveMsg(message, msgType.FILE);
- }
-
- calcUnReadSpot(message);
- ack(message);
- }
- },
-
- // 各种异常
- onError(error) {
- console.log(error); // 16: server-side close the websocket connection
- // if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
- // // if(error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED && !logout){
- // // if(WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax){
- // // return;
- // // }
- // uni.showToast({
- // title: "websocket 断开",
- // duration: 1000
- // });
- // uni.redirectTo({
- // url: "../login/login"
- // });
- // logout = true;
- // return;
- // } // 8: offline by multi login
-
- // if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
- // uni.showToast({
- // title: "offline by multi login",
- // duration: 1000
- // });
- // uni.redirectTo({
- // url: "../login/login"
- // });
- // }
-
- if (error.type == WebIM.statusCode.WEBIM_CONNCTION_OPEN_ERROR) {
- uni.hideLoading();
- disp.fire("em.error.passwordErr"); // uni.showModal({
- // title: "用户名或密码错误",
- // confirmText: "OK",
- // showCancel: false
- // });
- }
-
- if (error.type == WebIM.statusCode.WEBIM_CONNCTION_AUTH_ERROR) {
- uni.hideLoading();
- disp.fire("em.error.tokenErr");
- }
-
- if (error.type == "socket_error") {
- ///sendMsgError
- console.log("socket_errorsocket_error", error);
- /* uni.showToast({
- title: "网络已断开",
- icon: "none",
- duration: 2000,
- }); */
- disp.fire("em.error.sendMsgErr", error);
- }
- },
- });
- this.globalData.checkIsIPhoneX();
- },
- onShow: function() {
- console.log('App Show')
- },
- onHide: function() {
- console.log('App Hide')
- },
- methods: {
- /* HXlisten(){
- console.log('<<<<<<环信监听',uni.WebIM)
- uni.WebIM.conn.listen({
- onOpened: function () {
- console.log('>>>>>>环信登录成功啦')
- }, //连接成功回调
- onClosed: function () {
- console.log("<<<<<连接关闭");
- }, //连接关闭回调
- onTextMessage: function ( message ) {
- console.log("收到文本消息",message);
- }, //收到文本消息
- onEmojiMessage: function ( message ) {
- console.log("收到表情消息",message);
- }, //收到表情消息
- onPictureMessage: function ( message ) {
- console.log("收到图片消息",message);
- }, //收到图片消息
- onCmdMessage: function ( message ) {
- console.log("收到命令消息",message);
- }, //收到命令消息
- onAudioMessage: function ( message ) {
- console.log("收到音频消息",message);
- }, //收到音频消息
- onLocationMessage: function ( message ) {
- console.log("收到位置消息",message);
- },//收到位置消息
- onFileMessage: function ( message ) {
- console.log("收到文件消息",message);
- }, //收到文件消息
- onCustomMessage: function ( message ) {
- console.log("收到自定义消息",message);
- }, //收到自定义消息
- onVideoMessage: function (message) {
- var node = document.getElementById('privateVideo');
- var option = {
- url: message.url,
- headers: {
- 'Accept': 'audio/mp4'
- },
- onFileDownloadComplete: function (response) {
- var objectURL = uni.WebIM.utils.parseDownloadResponse.call(conn, response);
- node.src = objectURL;
- },
- onFileDownloadError: function () {
- console.log('File down load error.')
- }
- };
- uni.WebIM.utils.download.call(conn, option);
- }, //收到视频消息
- onPresence: function ( message ) {
- console.log('处理“广播”或“发布-订阅”消息',message);
- }, //处理“广播”或“发布-订阅”消息,如联系人订阅请求、处理群组、聊天室被踢解散等消息
- onRoster: function ( message ) {
- console.log('处理好友申请',message);
- }, //处理好友申请
- onInviteMessage: function ( message ) {
- console.log('处理群组邀请',message);
- }, //处理群组邀请
- onOnline: function () {
- console.log('本机网络连接成功');
- }, //本机网络连接成功
- onOffline: function () {
- console.log("本机网络掉线",message);
- }, //本机网络掉线
- onError: function ( message ) {
- console.log("失败回调:",message);
- }, //失败回调
- onBlacklistUpdate: function (list) { //黑名单变动
- // 查询黑名单,将好友拉黑,将好友从黑名单移除都会回调这个函数,list则是黑名单现有的所有好友信息
- console.log(list);
- },
- onRecallMessage: function(message){
- console.log("收到撤回消息回调",message);
- }, //收到撤回消息回调
- onReceivedMessage: function(message){
- console.log("收到消息送达服务器回执",message);
- }, //收到消息送达服务器回执
- onDeliveredMessage: function(message){
- console.log("收到消息送达客户端回执",message);
- }, //收到消息送达客户端回执
- onReadMessage: function(message){
- console.log("收到消息已读回执",message);
- }, //收到消息已读回执
- onCreateGroup: function(message){
- console.log("创建群组成功回执",message);
- }, //创建群组成功回执(需调用createGroupNew)
- onMutedMessage: function(message){
- console.log("禁言",message);
- }, //如果用户在A群组被禁言,在A群发消息会走这个回调并且消息不会传递给群其它成员
- onChannelMessage: function(message){
- console.log("收到整个会话已读的回执",message);
- } //收到整个会话已读的回执,在对方发送channel ack时会在这个回调里收到消息
- });
- }, */
- HXlogin() {
- var userId = uni.getStorageSync('myUsername')
- var options = {
- user: userId,
- pwd : '12345678',
- appKey: uni.WebIM.config.appkey,
- success: function() {
- var lianjie = uni.WebIM.conn.isOpened()
- var my = uni.getStorageSync("myUsername");
- uni.setStorageSync('myUsername',my)
- },
- error: function() {
-
- }
- }
- uni.WebIM.conn.open(options);
-
- }
- }
- }
- </script>
- <style lang="scss">
- /*每个页面公共css */
- @import "uview-ui/index.scss";
-
- .content {
- background-color: #ffffff;
- width: 100%;
- min-height: 100vh;
- display: flex;
- flex-direction: column;
- font-size: 28rpx;
- color: #333;
- box-sizing: border-box;
- }
- .hflex {
- display: flex;
- flex-direction: row;
- flex-wrap: nowrap;
- }
- .vflex {
- display: flex;
- flex-direction: column;
- flex-wrap: nowrap;
- }
- .jbetween {
- justify-content: space-between;
- }
- .jaround {
- justify-content: space-around;
- }
- .jend {
- justify-content: flex-end;
- }
- .jcenter {
- justify-content: center;
- }
- .acenter {
- align-items: center;
- }
- .abetween {
- align-content: space-between;
- }
- .astart {
- align-items: flex-start;
- }
- .aend {
- align-items: flex-end;
- }
- .fwrap {
- flex-wrap: wrap;
- }
- .text_hide {
- overflow: hidden;
- white-space: nowrap;
- text-overflow: ellipsis;
- }
- .text_hide2 {
- text-overflow: -o-ellipsis-lastline;
- overflow: hidden;
- text-overflow: ellipsis;
- display: -webkit-box;
- -webkit-line-clamp: 2;
- line-clamp: 2;
- -webkit-box-orient: vertical;
- }
- </style>
|