Commit 12222b89 by 施宇

111

parent 5e0f3af4
Showing with 2172 additions and 117 deletions
//app.js
const WebIM = require("utils/WebIM")["default"];
let msgStorage = require("components/chat/msgstorage");
let msgType = require("components/chat/msgtype");
let disp = require("utils/broadcast");
function calcUnReadSpot(message) {
let myName = wx.getStorageSync("myUsername");
let allMembers = wx.getStorageSync("member") || []; //好友
let count = allMembers.reduce(function (result, curMember, idx) {
let chatMsgs = wx.getStorageSync(curMember.toLowerCase() + myName.toLowerCase()) || [];
return result + chatMsgs.length;
}, 0);
getApp().globalData.unReadMessageNum = count;
disp.fire("em.xmpp.unreadspot", message);
}
function onMessageError(err) {
if (err.type === "error") {
wx.showToast({
title: err.errorText
});
return false;
}
return true;
}
function addMember(id) {
let member = wx.getStorageSync("member") || [];
let index = member.indexOf(id);
if (index == -1) {
member.push(id)
}
wx.setStorage({
key: "member",
data: member
});
}
App({
onLaunch: function () {
// 展示本地存储能力
// var logs = wx.getStorageSync('logs') || []
// logs.unshift(Date.now())
// wx.setStorageSync('logs', logs)
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
globalData: {
unReadMessageNum: 0,
},
conn: {
closed: false,
curOpenOpt: {},
open(opt) {
wx.showLoading({
title: '正在初始化客户端...',
mask: true
})
this.curOpenOpt = opt;
WebIM.conn.open(opt);
this.closed = false;
},
reopen() {
if (this.closed) {
WebIM.conn.open(this.curOpenOpt);
this.closed = false;
}
})
// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
},
onLaunch() {
let me = this;
wx.setStorage({
key: "myUsername",
data: '18271408717'
});
this.conn.open({
apiUrl: WebIM.config.apiURL,
user: '18271408717',
pwd: '123456',
appKey: WebIM.config.appkey
});
WebIM.conn.listen({
onOpened(message) {
},
onReconnect() {
wx.showToast({
title: "重连中...",
duration: 2000
});
},
onSocketConnected() {
wx.showToast({
title: "socket连接成功",
duration: 2000
});
},
onClosed() {
wx.showToast({
title: "网络已断开",
icon: 'none',
duration: 2000
});
me.conn.closed = true;
WebIM.conn.close();
},
onCmdMessage(message) {
},
onTextMessage(message) {
addMember(message.from)
if (message) {
if (onMessageError(message)) {
msgStorage.saveReceiveMsg(message, msgType.TEXT);
console.log('hahaha')
}
calcUnReadSpot(message);
}
}
},
onPictureMessage(message) {
},
// 各种异常
onError(error) {
console.log(error)
},
})
},
globalData: {
userInfo: null
}
})
\ No newline at end of file
});
{
"pages": [
"pages/tab/message/message",
"pages/tab/home/home",
"pages/form/good/index",
"pages/tab/good/good",
......@@ -8,14 +9,14 @@
"pages/list/bj/index",
"pages/list/xj/index",
"pages/login/index",
"pages/tab/message/message",
"pages/tab/me/me",
"pages/search/index/index",
"pages/search/result/index",
"pages/form/xj/index",
"pages/detail/good/index",
"pages/detail/xj/index",
"pages/list/qd/index"
"pages/list/qd/index",
"pages/detail/chat/index"
],
"window": {
"backgroundTextStyle": "light",
......
let msgStorage = require("msgstorage");
let msgType = require("msgtype");
Component({
properties: {
username: {
type: Object,
value: {},
},
chatType: {
type: String,
value: msgType.chatType.SINGLE_CHAT,
},
},
data: {
__comps__: {
msglist: null,
inputbar: null,
audio: null,
},
},
methods: {
toggleRecordModal(){
this.data.__comps__.audio.toggleRecordModal();
},
normalScroll(){
this.data.__comps__.msglist.normalScroll();
this.data.__comps__.inputbar.cancelEmoji();
},
shortScroll(){
this.data.__comps__.msglist.shortScroll();
},
saveSendMsg(evt){
msgStorage.saveMsg(evt.detail.msg, evt.detail.type);
this.data.__comps__.inputbar.cancelEmoji();
},
getMore(){
this.selectComponent('#chat-msglist').getHistoryMsg()
},
},
// lifetimes
created(){},
attached(){},
ready(){
this.data.__comps__.inputbar = this.selectComponent("#chat-inputbar");
this.data.__comps__.msglist = this.selectComponent("#chat-msglist");
this.data.__comps__.audio = this.selectComponent("#chat-suit-audio");
},
moved(){},
detached(){
},
});
{
"component": true,
"usingComponents": {
"chat-msglist": "msglist/msglist",
"chat-inputbar": "inputbar/inputbar"
}
}
<view class="main">
<chat-suit-audio
id="chat-suit-audio"
username="{{ username }}"
chatType="{{ chatType }}"
bind:newAudioMsg="saveSendMsg"></chat-suit-audio>
<chat-msglist
id="chat-msglist"
username="{{ username }}"
bind:msglistTap="normalScroll"></chat-msglist>
</view>
<chat-inputbar
id="chat-inputbar"
username="{{ username }}"
chatType="{{ chatType }}"
bind:newTextMsg="saveSendMsg"
bind:newImageMsg="saveSendMsg"
bind:newLocationMsg="saveSendMsg"
bind:newVideoMsg="saveSendMsg"
bind:tapSendAudio="toggleRecordModal"
bind:inputFocused="shortScroll"
bind:inputBlured="normalScroll"></chat-inputbar>
.main {
width: 100%;
height: 100%;
}
let msgType = require("../msgtype");
Component({
properties: {
username: {
type: Object,
value: {}
},
chatType: {
type: String,
value: msgType.chatType.SINGLE_CHAT,
},
},
data: {
__comps__: {
main: null,
emoji: null,
image: null,
},
},
methods: {
// 事件有长度限制:仅限 26 字符
toggleRecordModal(){
this.triggerEvent(
"tapSendAudio",
null,
{
bubbles: true,
composed: true
}
);
},
// sendVideo(){
// this.data.__comps__.video.sendVideo();
// },
openCamera(){
this.data.__comps__.image.openCamera();
},
openEmoji(){
this.data.__comps__.emoji.openEmoji();
},
cancelEmoji(){
this.data.__comps__.emoji.cancelEmoji();
},
sendImage(){
this.data.__comps__.image.sendImage();
},
emojiAction(evt){
this.data.__comps__.main.emojiAction(evt.detail.msg);
},
},
// lifetimes
created(){},
attached(){},
moved(){},
detached(){},
ready(){
this.setData({
isIPX: getApp().globalData.isIPX
})
let comps = this.data.__comps__;
comps.main = this.selectComponent("#chat-suit-main");
comps.emoji = this.selectComponent("#chat-suit-emoji");
comps.image = this.selectComponent("#chat-suit-image");
},
});
{
"component": true,
"usingComponents": {
"chat-suit-emoji": "suit/emoji/emoji",
"chat-suit-image": "suit/image/image",
"chat-suit-main": "suit/main/main"
}
}
<view class="room_bar">
<chat-suit-emoji id="chat-suit-emoji" bind:newEmojiStr="emojiAction"></chat-suit-emoji>
<chat-suit-main id="chat-suit-main" username="{{ username }}" chatType="{{ chatType }}" bind:inputFocused="cancelEmoji"></chat-suit-main>
<chat-suit-image id="chat-suit-image" username="{{ username }}" chatType="{{ chatType }}"></chat-suit-image>
<view class="other_func {{isIPX? 'other_func_X': ''}}">
<view class="open_emoji" bind:tap="openEmoji">
<image src="../../../images/Emoji.png"/>
</view>
<view class="send_image" bind:tap="sendImage">
<image src="../../../images/pic.png" style="height:20px; width: 20px"/>
</view>
</view>
</view>
.room_bar {
width: 100%;
height: auto;
border-top: 1px solid #CFCFCF;
position: fixed;
bottom: 0;
right: 0;
z-index: 1;
background-color: #FFFFFF;
transform: translateZ(1000px);
}
.other_func {
width: 100%;
height: 60rpx;
display: flex;
}
.other_func_X{
height: 128rpx;
}
.other_func image {
width: 42rpx;
height: 40rpx;
}
.open_emoji,
.send_image,
.open_camera,
.v-record {
width: 48rpx;
height: 48rpx;
display: flex;
align-items: center;
justify-content: center;
margin-left: 48rpx;
}
.v-record .icon-record {
width: 18rpx;
height: 40rpx;
}
.v-record{
margin-left: 48rpx;
}
.open_camera, .send_image{
margin-left: 64rpx;
}
let WebIM = require("../../../../../utils/WebIM")["default"];
let msgType = require("../../../msgtype");
let EMOJI_STATUS = {
OPENED: "showEmoji",
CLOSED: "emoji_list",
};
Component({
data: {
show: EMOJI_STATUS.CLOSED,
emoji: WebIM.Emoji,
emojiObj: WebIM.EmojiObj,
interval: 5000,
duration: 1000,
autoplay: false,
indicatorDots: true, // 显示面板指示点
},
methods: {
openEmoji(){
this.setData({
show: EMOJI_STATUS.OPENED
});
},
cancelEmoji(){
this.setData({
show: EMOJI_STATUS.CLOSED
});
},
// 输出 emoji
sendEmoji(event){
var emoji = event.target.dataset.emoji;
this.triggerEvent(
"newEmojiStr",
{
msg: emoji,
type: msgType.EMOJI,
},
{
bubbles: true,
composed: true
}
);
},
},
});
<swiper
class="{{ show }}"
indicator-dots="{{ indicatorDots }}"
autoplay="{{ autoplay }}"
interval="{{ interval }}"
duration="{{ duration }}">
<block>
<swiper-item>
<view class="emoji_item">
<image
wx:for="{{ emojiObj.map1 }}"
src="{{ emojiObj.path + item }}"
wx:key=""
bind:tap="sendEmoji"
data-emoji="{{ index }}" />
</view>
<view class="emoji_item">
<image
wx:for="{{ emojiObj.map2 }}"
src="{{ emojiObj.path + item }}"
wx:key=""
bind:tap="sendEmoji"
data-emoji="{{ index }}" />
</view>
<view class="emoji_item">
<image
wx:for="{{ emojiObj.map3 }}"
src="{{ emojiObj.path + item }}"
wx:key=""
bind:tap="sendEmoji"
data-emoji="{{ index }}" />
</view>
</swiper-item>
</block>
<block class="second">
<swiper-item>
<view class="emoji_item">
<image
wx:for="{{ emojiObj.map4 }}"
src="{{ emojiObj.path + item }}"
wx:key=""
bind:tap="sendEmoji"
data-emoji="{{ index }}" />
</view>
<view class="emoji_item">
<image
wx:for="{{ emojiObj.map5 }}"
src="{{ emojiObj.path + item }}"
wx:key=""
bind:tap="sendEmoji"
data-emoji="{{ index }}" />
</view>
<view class="emoji_item">
<image
wx:for="{{ emojiObj.map6 }}"
src="{{ emojiObj.path + item }}"
wx:key=""
bind:tap="sendEmoji"
data-emoji="{{ index }}" />
</view>
</swiper-item>
</block>
</swiper>
.emoji_list {
margin-top: 30px;
width: 100%;
height: 145px;
background-color: #dddddd;
padding-top: 10px;
padding-left: 3%;
display: none;
}
.showEmoji {
margin-top: 30px;
width: 100%;
height: 145px;
background-color: #dddddd;
padding-top: 10px;
padding-left: 3%;
display: block;
}
.emoji_list image,
.showEmoji image {
width: 26px;
height: 26px;
margin: 5px 2%;
}
.emoji {
width: 26px;
height: 26px;
margin: 0 0;
}
.emoji_item {
display: flex;
justify-content: space-around;
margin-right: 20px;
}
let WebIM = require("../../../../../utils/WebIM")["default"];
let msgType = require("../../../msgtype");
let disp = require("../../../../../utils/broadcast");
Component({
properties: {
username: {
type: Object,
value: {},
},
chatType: {
type: String,
value: msgType.chatType.SINGLE_CHAT,
},
},
data: {
},
methods: {
openCamera(){
var me = this;
wx.chooseImage({
count: 1,
sizeType: ["original", "compressed"],
sourceType: ["camera"],
success(res){
me.upLoadImage(res);
}
});
},
sendImage(){
var me = this;
wx.chooseImage({
count: 1,
sizeType: ["original", "compressed"],
sourceType: ["album"],
success(res){
me.upLoadImage(res);
},
});
},
isGroupChat(){
return this.data.chatType == msgType.chatType.CHAT_ROOM;
},
getSendToParam(){
return this.isGroupChat() ? this.data.username.groupId : this.data.username.your;
},
upLoadImage(res){
var me = this;
var tempFilePaths = res.tempFilePaths;
var token = WebIM.conn.context.accessToken
wx.getImageInfo({
src: res.tempFilePaths[0],
success(res){
var allowType = {
jpg: true,
gif: true,
png: true,
bmp: true
};
var str = WebIM.config.appkey.split("#");
var width = res.width;
var height = res.height;
var index = res.path.lastIndexOf(".");
var filetype = (~index && res.path.slice(index + 1)) || "";
if(filetype.toLowerCase() in allowType){
wx.uploadFile({
url: "https://a1.easemob.com/" + str[0] + "/" + str[1] + "/chatfiles",
filePath: tempFilePaths[0],
name: "file",
header: {
"Content-Type": "multipart/form-data",
Authorization: "Bearer " + token
},
success(res){
var data = res.data;
var dataObj = JSON.parse(data);
var id = WebIM.conn.getUniqueId(); // 生成本地消息 id
var msg = new WebIM.message(msgType.IMAGE, id);
var file = {
type: msgType.IMAGE,
size: {
width: width,
height: height
},
url: dataObj.uri + "/" + dataObj.entities[0].uuid,
filetype: filetype,
filename: tempFilePaths[0]
};
msg.set({
apiUrl: WebIM.config.apiURL,
body: file,
from: me.data.username.myName,
to: me.getSendToParam(),
roomType: false,
chatType: me.data.chatType,
success: function (argument) {
disp.fire('em.chat.sendSuccess', id);
}
});
if(me.data.chatType == msgType.chatType.CHAT_ROOM){
msg.setGroup("groupchat");
}
WebIM.conn.send(msg.body);
me.triggerEvent(
"newImageMsg",
{
msg: msg,
type: msgType.IMAGE
},
{
bubbles: true,
composed: true
}
);
}
});
}
}
});
},
},
});
let WebIM = require("../../../../../utils/WebIM")["default"];
let msgType = require("../../../msgtype");
let disp = require("../../../../../utils/broadcast");
Component({
properties: {
username: {
type: Object,
value: {},
},
chatType: {
type: String,
value: msgType.chatType.SINGLE_CHAT,
},
},
data: {
inputMessage: "", // render input 的值
userMessage: "", // input 的实时值
},
methods: {
focus(){
this.triggerEvent("inputFocused", null, { bubbles: true });
},
blur(){
this.triggerEvent("inputBlured", null, { bubbles: true });
},
isGroupChat(){
return this.data.chatType == msgType.chatType.CHAT_ROOM;
},
getSendToParam(){
return this.isGroupChat() ? this.data.username.groupId : this.data.username.your;
},
// bindinput 不能打冒号!
bindMessage(e){
this.setData({
userMessage: e.detail.value
});
},
emojiAction(emoji){
var str;
var msglen = this.data.userMessage.length - 1;
if(emoji && emoji != "[del]"){
str = this.data.userMessage + emoji;
}
else if(emoji == "[del]"){
let start = this.data.userMessage.lastIndexOf("[");
let end = this.data.userMessage.lastIndexOf("]");
let len = end - start;
if(end != -1 && end == msglen && len >= 3 && len <= 4){
str = this.data.userMessage.slice(0, start);
}
else{
str = this.data.userMessage.slice(0, msglen);
}
}
this.setData({
userMessage: str,
inputMessage: str
});
},
sendMessage(){
let me = this;
String.prototype.trim=function()
{
return this.replace(/(^\s*)|(\s*$)/g, '');
}
if(!this.data.userMessage.trim()){
return;
}
let id = WebIM.conn.getUniqueId();
let msg = new WebIM.message(msgType.TEXT, id);
msg.set({
msg: this.data.userMessage,
from: this.data.username.myName,
to: this.getSendToParam(),
roomType: false,
chatType: this.data.chatType,
success(id, serverMsgId){
//console.log('成功了')
disp.fire('em.chat.sendSuccess', id, me.data.userMessage);
},
fail(id, serverMsgId){
console.log('失败了')
}
});
if(this.data.chatType == msgType.chatType.CHAT_ROOM){
msg.setGroup("groupchat");
}
WebIM.conn.send(msg.body);
this.triggerEvent(
"newTextMsg",
{
msg: msg,
type: msgType.TEXT,
},
{
bubbles: true,
composed: true
}
);
//
this.setData({
userMessage: "",
inputMessage: "",
});
},
},
// lifetimes
created(){},
attached(){},
moved(){},
detached(){},
ready(){},
});
<!-- <chat-suit-emoji id="chat-suit-emoji" bind:newEmojiStr="emojiAction"></chat-suit-emoji> -->
<form class="text-input">
<view class="f-row">
<input
class="f news"
type="text"
value="{{ inputMessage }}"
cursor-spacing="65"
confirm-type="send"
bindconfirm="sendMessage"
bindinput="bindMessage"
bindtap="focus"
bindfocus="focus"
bindblur="blur"
placeholder="输入新消息"
placeholder-style="color:#CFCFCF; padding-left:5px;"
/>
<button class="send_btn" bind:tap="sendMessage">发送</button>
</view>
</form>
.text-input {
width: 100%;
height: 100rpx;
padding: 0;
display: block;
}
.news {
width: 100%;
height: 62rpx;
font-size: 14px;
padding: 0 32rpx;
display: inline-block;
margin-top: 10rpx;
line-height: 48rpx;
position:relative;
top: 0;
}
.send_btn {
width: 80rpx;
height: 60rpx;
line-height: 60rpx;
font-size: 17px;
color: #000;
padding: 0;
display: inline-block;
float: right;
margin: 8rpx 16rpx auto auto;
background-color: #fff;
}
.f-row{
height:100rpx;
display:flex;
align-items:center;
}
let msgStorage = require("../msgstorage");
let disp = require("../../../utils/broadcast");
let LIST_STATUS = {
SHORT: "scroll_view_change",
NORMAL: "scroll_view"
};
let page = 0;
let Index = 0;
let curMsgMid = ''
let isFail = false
Component({
properties: {
username: {
type: Object,
value: {},
},
},
data: {
view: LIST_STATUS.NORMAL,
toView: "",
chatMsg: [],
__visibility__: false,
},
methods: {
normalScroll(){
this.setData({
view: LIST_STATUS.NORMAL
});
},
shortScroll(){
this.setData({
view: LIST_STATUS.SHORT
});
},
onTap(){
this.triggerEvent("msglistTap", null, { bubbles: true });
},
previewImage(event){
var url = event.target.dataset.url;
wx.previewImage({
urls: [url] // 需要预览的图片 http 链接列表
});
},
getHistoryMsg(){
let me = this
let username = this.data.username;
let myUsername = wx.getStorageSync("myUsername");
let sessionKey = username.groupId ? username.groupId + myUsername : username.your + myUsername;
let historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || [];
if (Index < historyChatMsgs.length) {
let timesMsgList = historyChatMsgs.slice(-Index-10, -Index)
this.setData({
chatMsg: timesMsgList.concat(me.data.chatMsg),
toView: timesMsgList[timesMsgList.length - 1].mid,
});
Index += timesMsgList.length;
if (timesMsgList.length == 10) {
page ++
}
wx.stopPullDownRefresh()
}
},
renderMsg(renderableMsg, type, curChatMsg, sessionKey, isnew){
let me = this
if (curChatMsg.length > 1) {
this.data.chatMsg.map(function(elem, index) {
curChatMsg.map(function(item, i) {
if(elem.mid == item.mid){
//me.data.chatMsg.splice(index, 1)
curChatMsg.splice(i, 1)
}
})
})
}
var historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || [];
// if (curChatMsg.length) {
// console.log(curMsgMid.substring(curMsgMid.length - 10) , curChatMsg[0].mid.substring(curChatMsg[0].mid.length - 10))
// }
// if(curChatMsg.length && curMsgMid.substring(curMsgMid.length - 10) == curChatMsg[curChatMsg.length - 1].mid.substring(curChatMsg[0].mid.length - 10)){
// //curChatMsg[curChatMsg.length - 1].msg.data[0].isSuc = true
// curChatMsg[curChatMsg.length - 1].isSuc = true
// }
historyChatMsgs = historyChatMsgs.concat(curChatMsg);
//console.log('当前历史',renderableMsg)
//console.log('历史消息', historyChatMsgs)
if(!historyChatMsgs.length) return;
if (isnew == 'newMsg') {
this.setData({
chatMsg: this.data.chatMsg.concat(curChatMsg),
// 跳到最后一条
toView: historyChatMsgs[historyChatMsgs.length - 1].mid,
});
}else{
this.setData({
chatMsg: historyChatMsgs.slice(-10),
// 跳到最后一条
toView: historyChatMsgs[historyChatMsgs.length - 1].mid,
});
}
wx.setStorageSync("rendered_" + sessionKey, historyChatMsgs);
let chatMsg = wx.getStorageSync(sessionKey) || [];
chatMsg.map(function(item, index) {
curChatMsg.map(function(item2, index2) {
if (item2.mid == item.mid) {
chatMsg.splice(index, 1)
}
})
})
wx.setStorageSync(sessionKey, chatMsg);
Index = historyChatMsgs.slice(-10).length;
wx.pageScrollTo({
scrollTop: 9999,
})
if (isFail) {
this.renderFail(sessionKey)
}
},
renderFail(sessionKey){
let me = this
let msgList = me.data.chatMsg
msgList.map((item) =>{
if (item.mid.substring(item.mid.length - 10) == curMsgMid.substring(curMsgMid.length - 10)) {
item.msg.data[0].isFail = true
item.isFail = true
me.setData({
chatMsg: msgList
})
}
})
if (me.curChatMsg[0].mid == curMsgMid) {
me.curChatMsg[0].msg.data[0].isShow = false;
me.curChatMsg[0].isShow = false
}
wx.setStorageSync("rendered_" + sessionKey, msgList);
isFail = false
}
},
// lifetimes
created(){
},
attached(){
this.__visibility__ = true;
page = 0;
Index = 0;
},
moved(){},
detached(){
this.__visibility__ = false;
},
ready(event){
let me = this;
if (getApp().globalData.isIPX) {
this.setData({
isIPX: true
})
}
let username = this.data.username;
let myUsername = wx.getStorageSync("myUsername");
let sessionKey = username.groupId
? username.groupId + myUsername
: username.your + myUsername;
let chatMsg = wx.getStorageSync(sessionKey) || [];
this.renderMsg(null, null, chatMsg, sessionKey);
wx.setStorageSync(sessionKey, null);
// disp.on("em.chat.sendSuccess", function(mid){
// curMsgMid = mid
// console.log('发送过去了', mid)
// let msgList = me.data.chatMsg
// msgList.map((item) =>{
// if (item.mid.substring(item.mid.length - 10) == mid.substring(mid.length - 10)) {
// console.log(111111, item)
// item.msg.data[0].isSuc = true
// item.isSuc = true
// me.setData({
// chatMsg: msgList
// })
// }
// })
// if (me.curChatMsg[0].mid == curMsgMid) {
// me.curChatMsg[0].msg.data[0].isShow = true
// me.curChatMsg[0].isShow = true
// }
// wx.setStorageSync("rendered_" + sessionKey, msgList);
// console.log('msgList', msgList)
// })
disp.on('em.xmpp.error.sendMsgErr', function(err) {
curMsgMid = err.data.mid
isFail = true
return
console.log('发送失败了')
let msgList = me.data.chatMsg
msgList.map((item) =>{
if (item.mid.substring(item.mid.length - 10) == curMsgMid.substring(curMsgMid.length - 10)) {
item.msg.data[0].isFail = true
item.isFail = true
me.setData({
chatMsg: msgList
})
}
})
if (me.curChatMsg[0].mid == curMsgMid) {
me.curChatMsg[0].msg.data[0].isShow = false;
me.curChatMsg[0].isShow = false
}
wx.setStorageSync("rendered_" + sessionKey, msgList);
});
msgStorage.on("newChatMsg", function(renderableMsg, type, curChatMsg, sesskey){
me.curChatMsg = curChatMsg;
if(!me.__visibility__) return;
// 判断是否属于当前会话
if(username.groupId){
// 群消息的 to 是 id,from 是 name
if(renderableMsg.info.from == username.groupId || renderableMsg.info.to == username.groupId){
if (sesskey == sessionKey) {
me.renderMsg(renderableMsg, type, curChatMsg, sessionKey, 'newMsg');
}
}
}
else if(renderableMsg.info.from == username.your || renderableMsg.info.to == username.your){
if (sesskey == sessionKey) {
me.renderMsg(renderableMsg, type, curChatMsg, sessionKey, 'newMsg');
}
}
});
},
});
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file
<template name="txt">
<text class="msg-text" style="float:left;">{{ item.data }}</text>
</template>
<template name="emoji">
<image
class="avatar"
src="{{ '../../../images/faces/' + item.data }}"
style="width:25px; height:25px; margin:0 0 2px 0; float:left;" />
</template>
<template name="img">
<image
class="avatar"
src="{{ item.msg.data }}"
style="width:90px; height:120px; margin:2px auto;"
mode="aspectFit"
bind:tap="previewImage"
data-url="{{ item.msg.data }}" />
</template>
<template name="video">
<video src="{{ item.msg.data }}" controls autoplay />
</template>
<template name="audio">
<audio src="{{ item.msg.url }}" controls autoplay />
</template>
<!-- view 换成 scroll-view效果更好 用view是为了要stopPullDownRefresh -->
<view
scroll-y="true"
class="{{ view }} wrap {{isIPX?'scroll_view_X': ''}}"
bind:tap="onTap"
bindscroll="scrollmore"
bindscrolltoupper="refresh"
upper-threshold='-50'
scroll-into-view="{{ toView }}">
<view class="message" wx:for="{{ chatMsg }}" wx:key="{{ item.mid }}" id="{{ item.mid }}">
<!-- <view class="time">
<text class="time-text">{{ item.time }}</text>
</view> -->
<view class="main" class="{{ item.style }}">
<view class="user">
<!-- yourname:就是消息的 from -->
<text class="user-text">{{ item.yourname + ' ' + item.time}}</text>
</view>
<image class="avatar" src="../../../images/theme@2x.png"/>
<view class="msg">
<image
class="err {{(item.style == 'self' && item.isFail) ? 'show' : 'hide'}}"
src="../../../images/msgerr.png"/>
<image wx:if="{{item.style == 'self'}}" src="../../../images/poprightarrow@2x.png" class="msg_poprightarrow"/>
<image wx:if="{{item.style == ''}}" src="../../../images/popleftarrow@2x.png" class="msg_popleftarrow"/>
<view wx:if="{{ item.msg.type == 'img' || item.msg.type == 'video' }}">
<template is="{{ item.msg.type }}" data="{{ item }}"/>
</view>
<audio-msg
wx:if="{{ item.msg.type == 'audio' }}"
msg="{{ item }}"></audio-msg>
<view wx:elif="{{ item.msg.type == 'txt' || item.msg.type == 'emoji' }}">
<view class="template" wx:for="{{ item.msg.data }}" wx:key="">
<template is="{{ item.type }}" data="{{ item }}"/>
</view>
</view>
</view>
</view>
</view>
</view>
<view style="height: 1px;"></view>
/*.chat-bg{
position:fixed;
width: 100%;
height: 100%;
z-index: 0;
top: 50px;
}*/
.scroll_view,
.scroll_view_change {
/*width: 100%;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 150rpx;*/
margin-bottom: 174rpx;
background-color: #FAFAFA;
}
.scroll_view_X,
.scroll_view_change_X{
margin-bottom: 244rpx;
}
.scroll_view_change {
/*bottom: 440rpx;*/
margin-bottom: 590rpx;
}
.message {
width: 92%;
height: auto;
padding: 0 30rpx;
position: relative;
}
.time {
margin: 14rpx 0;
text-align: center;
}
.time .time-text {
display: inline-block;
padding: 6rpx 20rpx 0 20rpx;
font-size: 24rpx;
color: #fff;
line-height: 28rpx;
border-radius: 4rpx;
background-color: #dcdcdc;
}
.user .user-text {
margin: auto 100rpx 8rpx;
font-size: 20rpx;
color: #dcdcdc;
display: block;
}
.avatar {
width: 72rpx;
height: 72rpx;
margin: 0 20rpx 0 0;
border-radius: 6rpx;
float: left;
}
.msg {
display: inline-block;
padding: 20rpx;
max-width: calc(85% - 80rpx);
min-height: 40rpx;
font-size: 24rpx;
/*overflow: hidden;*/
text-align: left;
word-break: break-all;
background-color: #fff;
border-radius: 26rpx;
position: relative;
margin-top: 24rpx;
}
.msg .msg_poprightarrow {
position: absolute;
right: -10rpx;
height: 18rpx;
width: 18rpx;
margin-top: -10rpx;
}
.msg .msg_popleftarrow{
position:absolute;
left: -14rpx;
height: 18rpx;
width: 18rpx;
margin-top: -10rpx;
}
.msg .msg-text {
line-height: 40rpx;
font-size: 32rpx;
margin: 0;
}
/*.msg:before {
content: " ";
position: absolute;
top: 9px;
right: 100%;
border: 6px solid transparent;
border-right-color: #EDEDED;
}*/
.self {
text-align: right;
}
.self .avatar {
float: right;
margin: 0 0 0 20rpx;
}
.user {
position: relative;
bottom: -30rpx;
}
.self .msg {
background-color: #0873DE;
color: #fff;
}
.self .msg:before {
right: inherit;
left: 100%;
border-right-color: transparent;
border-left-color: #b2e281;
}
.template {
display: inline;
}
.err{
width: 32rpx;
height: 32rpx;
position: absolute;
left: -40rpx;
}
.hide{
display: none;
}
.show{
display: block;
}
let WebIM = require("../../utils/WebIM")["default"];
let msgType = require("msgtype");
module.exports = function(sendableMsg, type, myName){
var time = WebIM.time();
var renderableMsg = {
info: {
from: sendableMsg.body.from,
to: sendableMsg.body.to
},
username: sendableMsg.body.from == myName ? sendableMsg.body.to : sendableMsg.body.from,
yourname: sendableMsg.body.from,
msg: {
type: type,
url: sendableMsg.body.body.url,
data: getMsgData(sendableMsg, type),
},
style: sendableMsg.body.from == myName ? "self" : "",
time: time,
mid: sendableMsg.type + sendableMsg.id,
chatType: sendableMsg.body.chatType
};
if(type == msgType.IMAGE){
renderableMsg.msg.size = {
width: sendableMsg.body.body.size.width,
height: sendableMsg.body.body.size.height,
};
}else if (type == msgType.AUDIO) {
renderableMsg.msg.length = sendableMsg.body.length;
}else if (type == msgType.FILE){
renderableMsg.msg.data = [{data: "[当前不支持此格式消息展示]", type: "txt"}];
renderableMsg.msg.type = 'txt';
}
return renderableMsg;
function getMsgData(sendableMsg, type){
if(type == msgType.TEXT){
return WebIM.parseEmoji(sendableMsg.value.replace(/\n/mg, ""));
}
else if(type == msgType.EMOJI){
return sendableMsg.value;
}
else if(type == msgType.IMAGE || type == msgType.VIDEO || type == msgType.AUDIO){
return sendableMsg.body.body.url;
} else if (type == msgType.FILE) {
return sendableMsg.body.body.msg
}
return "";
}
};
let Disp = require("../../utils/Dispatcher");
let msgPackager = require("msgpackager");
let msgType = require("msgtype");
let msgStorage = new Disp();
let disp = require("../../utils/broadcast");
msgStorage.saveReceiveMsg = function(receiveMsg, type){
let sendableMsg;
if(type == msgType.IMAGE){
sendableMsg = {
id: receiveMsg.id,
type: type,
body: {
id: receiveMsg.id,
from: receiveMsg.from,
to: receiveMsg.to,
type: receiveMsg.type,
ext: receiveMsg.ext,
chatType: receiveMsg.type,
toJid: "",
body: {
type: type,
url: receiveMsg.url,
filename: receiveMsg.filename,
filetype: receiveMsg.filetype,
size: {
width: receiveMsg.width,
height: receiveMsg.height
},
},
},
};
}
else if(type == msgType.TEXT || type == msgType.EMOJI){
sendableMsg = {
id: receiveMsg.id,
type: type,
body: {
id: receiveMsg.id,
from: receiveMsg.from,
to: receiveMsg.to,
type: receiveMsg.type,
ext: receiveMsg.ext,
chatType: receiveMsg.type,
toJid: "",
body: {
type: type,
msg: receiveMsg.data,
},
},
value: receiveMsg.data
};
}
else if (type == msgType.FILE) {
sendableMsg = {
id: receiveMsg.id,
type: type,
body: {
id: receiveMsg.id,
length: receiveMsg.file_length,
from: receiveMsg.from,
to: receiveMsg.to,
type: receiveMsg.type,
ext: receiveMsg.ext,
chatType: receiveMsg.type,
toJid: "",
body: {
type: type,
url: receiveMsg.url,
filename: receiveMsg.filename,
msg: "当前不支持此格式消息展示",
},
},
value: receiveMsg.data
};
}
else if(type == msgType.AUDIO){
sendableMsg = {
id: receiveMsg.id,
type: type,
accessToken: receiveMsg.token || receiveMsg.accessToken,
body: {
id: receiveMsg.id,
length: receiveMsg.length,
from: receiveMsg.from,
to: receiveMsg.to,
type: receiveMsg.type,
ext: receiveMsg.ext,
chatType: type,
toJid: "",
body: {
type: type,
url: receiveMsg.url,
filename: receiveMsg.filename,
filetype: receiveMsg.filetype,
from: receiveMsg.from,
to: receiveMsg.to
},
},
};
}
else{
return;
}
this.saveMsg(sendableMsg, type, receiveMsg);
};
msgStorage.saveMsg = function(sendableMsg, type, receiveMsg){
//console.log('sendableMsgsendableMsg', sendableMsg)
let me = this;
let myName = wx.getStorageSync("myUsername");
let sessionKey;
// 仅用作群聊收消息,发消息没有 receiveMsg
if(receiveMsg && receiveMsg.type == "groupchat"){
sessionKey = receiveMsg.to + myName;
}
// 群聊发 & 单发 & 单收
else{
sessionKey = sendableMsg.body.from == myName
? sendableMsg.body.to + myName
: sendableMsg.body.from + myName;
}
let curChatMsg = wx.getStorageSync(sessionKey) || [];
let renderableMsg = msgPackager(sendableMsg, type, myName);
if(type == msgType.AUDIO) {
renderableMsg.msg.length = sendableMsg.body.length;
renderableMsg.msg.token = sendableMsg.accessToken;
}
curChatMsg.push(renderableMsg);
//console.log('renderableMsgrenderableMsg', renderableMsg)
if(type == msgType.AUDIO){
renderableMsg.msg.token = sendableMsg.accessToken;
//如果是音频则请求服务器转码
// wx.downloadFile({
// url: sendableMsg.body.body.url,
// header: {
// "X-Requested-With": "XMLHttpRequest",
// Accept: "audio/mp3",
// Authorization: "Bearer " + sendableMsg.accessToken
// },
// success(res){
// // wx.playVoice({
// // filePath: res.tempFilePath
// // });
// renderableMsg.msg.url = res.tempFilePath;
// save();
// },
// fail(e){
// console.log("downloadFile failed", e);
// }
// });
}
// else{
// save();
// }
save();
function save(){
wx.setStorage({
key: sessionKey,
data: curChatMsg,
success(){
if (type == msgType.AUDIO || type == msgType.VIDEO) {
disp.fire('em.chat.audio.fileLoaded');
}
me.fire("newChatMsg", renderableMsg, type, curChatMsg, sessionKey);
}
});
}
};
module.exports = msgStorage;
module.exports = {
IMAGE: "img",
TEXT: "txt",
LOCATION: "location",
VIDEO: "video",
AUDIO: "audio",
EMOJI: "emoji",
FILE: "chat",
//
chatType: {
SINGLE_CHAT: "singleChat",
CHAT_ROOM: "chatRoom",
},
};
let _compData = {
'_toast_.isHide': false,// 控制组件显示隐藏
'_toast_.content': ''// 显示的内容
}
let toastPannel = {
// toast显示的方法
toastSuccess: function (data) {
let self = this;
this.setData({ '_toast_.isHidescss': true, '_toast_.content': data });
setTimeout(function () {
self.setData({ '_toast_.isHidescss': false })//自定义方法,根据编辑需求
}, 2000)
},
toastFilled: function (data) {
let self = this;
this.setData({ '_toast_.isHidefil': true, '_toast_.content': data });
setTimeout(function () {
self.setData({ '_toast_.isHidefil': false })//自定义方法,根据编辑需求
}, 2000)
}
}
function ToastPannel() {//构造方法关联了当前页的方法及相关代码
// 拿到当前页面对象
let pages = getCurrentPages();
let curPage = pages[pages.length - 1];
this.__page = curPage;
// 小程序最新版把原型链干掉了。。。换种写法
Object.assign(curPage, toastPannel);
// 附加到page上,方便访问
curPage.toastPannel = this;
// 把组件的数据合并到页面的data对象中
curPage.setData(_compData);
return this;
}
module.exports = {
ToastPannel
}
\ No newline at end of file
<template name="toast">
<view class='toast_content_box'>
<view class="toast_content" wx:if="{{ isHidefil }}">
<view class="toast_content_border"></view>
<view class="toast_content_icon">
<image class="toast_icon_img" src="../../images/filled@2x.png"/>
</view>
<view class="toast_content_text">
{{content}}
</view>
</view>
<view class='toast_content_box'>
<view class="toast_content" wx:if="{{ isHidescss }}">
<view class="toast_content_border toast_success"></view>
<view class="toast_content_icon">
<image class="toast_icon_img" src="../../images/success@2x.png"/>
</view>
<view class="toast_content_text">
{{content}}
</view>
</view>
</view>
</view>
</template>
<!-- <template name="toast_success">
<view class='toast_content_box'>
<view class="toast_content" wx:if="{{ isHide }}">
<view class="toast_content_border"></view>
<view class="toast_content_icon">
<image class="toast_icon_img" src="../../images/success@2x.png"/>
</view>
<view class="toast_content_text">
{{content}}
</view>
</view>
</view>
</template> -->
\ No newline at end of file
.toast_content_box {
display: flex;
width: 100%;
justify-content: center;
align-items: center;
position: fixed;
z-index: 999;
top: 0;
left: 0;
}
.toast_content {
width: 80%;
padding: 30rpx;
border-radius: 10rpx;
height: 88rpx;
box-sizing:border-box;
overflow: hidden;
box-shadow: 0 8rpx 16rpx #BABABA;
background-color: #fff;
}
.toast_content_border{
width: 0px;
height: 80rpx;
border: 4rpx solid #CE3918;
position: relative;
left: -30rpx;
top: -30rpx;
}
.toast_success {
border: 4rpx solid #179F52;
}
.toast_content_icon{
width: 30rpx;
height: 30rpx;
position: relative;
top: -96rpx;
}
.toast_icon_img{
width: 30rpx;
height: 30rpx;
}
.toast_content_text {
height:100%;
width:100%;
color:#000;
font-size:28rpx;
text-align:center;
display:;
float:right;
position:absolute;
top:0;
line-height:88rpx;
text-align:left;
padding-left:50rpx;
}
\ No newline at end of file
// pages/detail/chat/index.js
let disp = require("../../../utils/broadcast");
Page({
data: {
username: {
your: "",
},
},
// options = 系统传入的 url 参数
onLoad(options) {
let username = JSON.parse(options.username);
this.setData({ username: username });
wx.setNavigationBarTitle({
title: username.your
});
},
onUnload() {
disp.fire("em.chatroom.leave");
},
onPullDownRefresh: function () {
wx.showNavigationBarLoading();
this.selectComponent('#chat').getMore()
// 停止下拉动作
wx.hideNavigationBarLoading();
wx.stopPullDownRefresh();
},
});
{
"navigationBarTitleText": "chatting",
"backgroundTextStyle": "dark",
"enablePullDownRefresh": true,
"usingComponents": {
"chat": "../../components/chat/chat"
}
}
\ No newline at end of file
<!--pages/detail/chat/index.wxml-->
<chat
id="chat"
username="{{ username }}"
chatType="singleChat"></chat>
/* pages/detail/chat/index.wxss */
\ No newline at end of file
// pages/tab/message/message.js
let disp = require("../../../utils/broadcast");
var WebIM = require("../../../utils/WebIM")["default"];
Page({
/**
* 页面的初始数据
*/
data: {
unReadSpotNum: 0,
arr: [],
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let me = this;
//监听未读消息数
disp.on("em.xmpp.unreadspot", function (message) {
console.log(111)
me.setData({
arr: me.getChatList(),
unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
});
});
},
getChatList() {
let array = [];
let member = wx.getStorageSync("member");
let myName = wx.getStorageSync("myUsername");
for (let i = 0; i < member.length; i++) {
let newChatMsgs = wx.getStorageSync(member[i] + myName) || [];
let historyChatMsgs = wx.getStorageSync("rendered_" + member[i] + myName) || [];
let curChatMsgs = historyChatMsgs.concat(newChatMsgs);
if (curChatMsgs.length) {
let lastChatMsg = curChatMsgs[curChatMsgs.length - 1];
lastChatMsg.unReadCount = newChatMsgs.length;
if (lastChatMsg.unReadCount > 99) {
lastChatMsg.unReadCount = "99+";
}
let dateArr = lastChatMsg.time.split(' ')[0].split('-')
let timeArr = lastChatMsg.time.split(' ')[1].split(':')
let month = dateArr[2] < 10 ? '0' + dateArr[2] : dateArr[2]
lastChatMsg.dateTimeNum = `${dateArr[1]}${month}${timeArr[0]}${timeArr[1]}${timeArr[2]}`
lastChatMsg.time = `${dateArr[1]}${dateArr[2]}${timeArr[0]}${timeArr[1]}分`
array.push(lastChatMsg);
}
}
array.sort((a, b) => {
return b.dateTimeNum - a.dateTimeNum
})
return array;
},
into_singleChatRoom: function (detail) {
var my = wx.getStorageSync("myUsername");
var nameList = {
myName: my,
your: detail.username
};
wx.navigateTo({
url: "/pages/detail/chat/index?username=" + JSON.stringify(nameList)
});
},
into_chatRoom: function (event) {
let detail = event.currentTarget.dataset.item;
this.into_singleChatRoom(detail)
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
......@@ -25,8 +79,12 @@ Page({
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
onShow: function () {
this.setData({
arr: this.getChatList(),
unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
});
},
/**
......
<!--pages/tab/message/message.wxml-->
<text>pages/tab/message/message.wxml</text>
<view class="message-view">
<view class="nodata" wx:if="{{arr.length == 0}}">
<cover-image src="/res/images/imgs/nomessage.png" class="img"></cover-image>
<view class="h3 bold">暂无询价消息</view>
</view>
<view class="message-content" wx:else>
<view class="tip row bothSide verCenter">
<view class="tip-left">
<text class="icon iconfont iconiconxiantiaoshouji12 tip-icon"></text>
<text class="tip-c">风险提示文字风险提示文字风险提示文字风险</text>
</view>
<text class="icon iconfont iconiconxiantiaoshouji13 close-icon"></text>
</view>
<view class="message-list">
<view class="message-item px-hr-bottom row verCenter bothSide nowrap" wx:for="{{ arr }}" wx:key="index" catchtap="into_chatRoom">
<view class="message-l row verCenter ellipsis">
<cover-image src="/res/images/imgs/iclogo.png" class="message-avar"></cover-image>
<view class="message-l-view ellipsis">
<view class="message-c bold ellipsis">{{ item.username }}</view>
<view class="message-t ellipsis">{{ item.msg.data[0].data }}</view>
</view>
</view>
<view class="message-r">
<view class="message-r-t">{{item.time}}</view>
<view class="message-r-n">{{ item.unReadCount }}</view>
</view>
</view>
</view>
</view>
</view>
\ No newline at end of file
/* pages/tab/message/message.wxss */
\ No newline at end of file
/* pages/tab/message/message.wxss */
.message-view{
overflow: hidden;
}
.tip {
padding: 12rpx 24rpx;
background-color: #fff6e6;
}
.tip .close-icon {
color: #d8dfe6;
}
.tip .icon {
font-size: 30rpx;
}
.tip-left {
color: #eaa217;
}
.tip-left .tip-icon {
margin-right: 7rpx;
vertical-align: middle;
}
.tip-c {
font-size: 24rpx;
}
.message-item {
margin-left: 25rpx;
padding: 24rpx 24rpx 24rpx 0;
}
.message-avar {
height: 68rpx;
width: 68rpx;
border-radius: 50% 50%;
}
.message-l-view {
margin-left: 24rpx;
}
.message-c {
color: #515559;
font-size: 28rpx;
}
.message-t {
font-size: 22rpx;
color: #8a9299;
margin-top: 4rpx;
}
.message-r {
font-size: 22rpx;
text-align: right;
}
.message-r-t {
color: #adb6bf;
padding-bottom: 12rpx;
}
.message-r-n {
color: #fff;
padding: 0rpx 10rpx;
border-radius: 15rpx;
display: inline;
background-color: #fc4c4c;
}
......@@ -4,13 +4,21 @@
"ignore": []
},
"setting": {
"urlCheck": true,
"urlCheck": false,
"es6": true,
"postcss": true,
"minified": true,
"newFeature": true,
"coverView": true,
"autoAudits": false,
"coverView": true
"checkInvalidKey": true,
"checkSiteMap": true,
"uploadWithSourceMap": true,
"babelSetting": {
"ignore": [],
"disablePlugins": [],
"outputPath": ""
}
},
"compileType": "miniprogram",
"libVersion": "2.7.0",
......
......@@ -531,7 +531,7 @@ function _login(options, conn) {
}
function callback(status, msg) {
console.log("connection stat change", status, msg);
// console.log("connection stat change", status, msg);
_loginCallback(status, msg, conn);
}
}
......@@ -738,7 +738,7 @@ connection.prototype.cacheReceiptsMessage = function (options) {
};
connection.prototype.open = function (options) {
let me = this;
console.log("open", this.isOpening());
// console.log("open", this.isOpening());
// 防止重复初始化
if (this.isOpening() || this.isOpened()) {
console.log("can't open [1]");
......
......@@ -5592,13 +5592,13 @@ var $pres = null;
}
},
success: function (e) {
console.log('连接成功', e)
// console.log('连接成功', e)
}
});
_socketTask = SocketTask;
_socketTask.onOpen(function (res) {
console.log("WebSocket 连接已打开!");
// console.log("WebSocket 连接已打开!");
isSocketConnnected = true
// wx.sendSocketMessage({
// data: "Hello,World:"
......
......@@ -614,14 +614,14 @@
data = null;
tempData = null;
}
console.log("wx.request", options.url);
// console.log("wx.request", options.url);
wx.request({
url: options.url,
data: options.data,
header: options.headers,
method: type,
success: function(res){
console.log("wx.request.success", arguments);
// console.log("wx.request.success", arguments);
if(res.statusCode == "200"){
suc(res);
}
......@@ -630,10 +630,10 @@
}
},
complete(){
console.log("wx.request.complete", arguments);
// console.log("wx.request.complete", arguments);
},
fail(){
console.log("wx.request.fail", arguments);
// console.log("wx.request.fail", arguments);
}
});
},
......
var obsCbs = obsCbs || [];
var obsObjs = obsObjs || [];
var cloneObjs = cloneObjs || [];
function newOne(obj){
obsObjs.push(obj);
obsCbs.push([]);
cloneObjs.push(Object.assign({}, obj));
}
module.exports = {
del(obj, cb){
let curObjIdx = obsObjs.indexOf(obj);
if(~curObjIdx){
let cbs = obsCbs[curObjIdx];
let curCbIdx = cbs.indexOf(cb);
if(~curCbIdx){
cbs.splice(curCbIdx, 1);
if(!cbs.length){
obsObjs.splice(curObjIdx, 1);
}
}
}
},
add(obj, cb){
let curIdx = obsObjs.indexOf(obj);
if(!~curIdx){
curIdx = obsObjs.length;
newOne(obj);
}
let cbs = obsCbs[curIdx];
cbs.push(cb);
for(let key in obj){
Object.defineProperty(obj, key, {
set: function(val){
cloneObjs[curIdx][key] = val;
for(let i = 0; i < cbs.length; i++){
cbs[i].apply(obj, [val, key]);
}
},
get: function(){
return cloneObjs[curIdx][key];
}
});
}
return obj;
},
};
......@@ -27,7 +27,7 @@ let config = {
/*
* Application AppKey
*/
appkey: "easemob-demo#chatdemoui",
appkey: "1113190618181018#icsales",
/*
* Whether to use HTTPS '1177161227178308#xcx'
* @parameter {Boolean} true or false
......@@ -38,7 +38,7 @@ let config = {
* true: A visitor can sign in to multiple webpages and receive messages at all the webpages.
* false: A visitor can sign in to only one webpage and receive messages at the webpage.
*/
isMultiLoginSessions: false,
isMultiLoginSessions: true,
/**
* Whether to use window.doQuery()
* @parameter {Boolean} true or false
......
const auth_url = 'http://authapi.icsales.cc';
const so_url = 'http://soapi.icsales.cc';
const offer_url = "http://offerapi.icsales.cc";
const user_url = 'http://userapi.icsales.cc';
const goods_url = 'http://goodsapi.icsales.cc';
const inquiry_url = 'http://inquiryapi.icsales.cc';
const index_url = 'http://www.icsales.cc';
const apis = {
/**
* 用户注册
*/
authRegister: auth_url + '/auth/register',
/**
* 账号密码登录
*/
authlogin: auth_url + '/auth/login',
/**
* 重置密码
*/
resetPassword: auth_url + '/auth/resetPassword',
/**
* 手机验证码快捷登录
*/
authMobilelogin: auth_url + '/auth/mobile/login',
/**
* 获取图形验证码接口
*/
captchaInfo: auth_url + '/captchaInfo',
/**
* 注册获取短信验证码接口
*/
getRegistCode: auth_url + '/v1/getRegistCode',
/**
* 退出
*/
authLogout: auth_url + '/auth/logout',
/***
* 获取用户基本信息
*/
authme: auth_url + '/auth/me',
/***
* 新增会员认证信息
*/
addAuth: user_url + '/user/addauth',
/***
* 更新会员认证信息
*/
editAuth: user_url + '/user/editauth',
/***
* 获取会员认证信息
*/
authInfo: user_url + '/user/authinfo',
/***
* 上传文件的接口
*/
ossupload: goods_url + '/oss/upload',
/**
* 商品列表
*/
goodsInfo: goods_url + '/goods/info',
/**
* 商品搜索
*/
goodsSearch: goods_url + '/goods/search',
/**
* 商品数量
*/
goodsCount: goods_url + '/goods/count',
/**
* 商品新增
*/
goodsAdd: goods_url + '/goods/add',
/**
* 批量上传
*/
bulkupload: goods_url + '/goods/upload',
/**
* 商品修改
*/
goodsSave: goods_url + '/goods/save',
/***
* 商品上下架
*/
goodsStatus: goods_url + "/goods/status",
/****
* 询价搜索 不需要token
*/
inquirySearch: offer_url + '/inquiry/search',
/***
* 会员中心询价列表 需要token
*/
inquiryInfo: offer_url + "/inquiry/info",
/***
* 我的询价回复
*/
inquiryMyOffer: offer_url + "/inquiry/my/offer",
/***
* 询价添加 需要token
*/
inquiryadd: offer_url + "/inquiry/add",
/***
* 询价上下架
*/
inquirystatussave: offer_url + "/inquiry/status/save",
/***
* 询价统计
*/
inquirycount: offer_url + "/inquiry/count",
/***
* 报价统计
*/
offercount: offer_url + "/offer/count",
/***
* 继续报价 and 回复报价
*/
offercontinue: offer_url + "/offer/continue",
/***
* 新增报价
*/
offeradd: offer_url + "/offer/add",
/***
* 价单列表(搜索)
*/
offersearch: offer_url + "/offer/search",
/***
* 我的报价单列表
*/
offerinfo: offer_url + "/offer/info",
/***
* 获取会员信息
*/
userInfo: user_url + "/user/info",
/***
* 账户消息通知设置
*/
userSetmsg: user_url + "/user/setmsg",
/***
* 账户设置
*/
userAccount: user_url + "/user/account",
/***
* 获取省市区
*/
regionPcd: user_url + "/region/pcd",
/**
* 批量上传商品列表
*/
uploadList: goods_url + '/goods/upload/list',
/**
* 数量统计
*/
countBusiness: user_url + '/count/business',
/**
* 获取会员系统通知
*/
userSysmsg: user_url + '/user/sysmsg',
/**
* 获取会员活动通知
*/
userActmsg: user_url + '/user/actmsg',
/**
* 标记会员通知(已读)
*/
userMarkmsg: user_url + '/user/markmsg'
}
export default apis
\ No newline at end of file
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
//数据请求(get)
const getData = (url, callBack) => {
wx.request({
url: getApp().globalUrl.baseUrl + url,
header: {
"Content-Type": "applciation/json"
},
success: (res) => {
callBack(true, res.data)
},
fail: (err) => {
callBack(false, err)
}
})
};
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
//数据请求(post)
const postData = (url, data, callBack) => {
showLoading("加载中", true)
var Url = getApp().globalUrl.baseUrl + url;
wx.request({
url: Url,
data: data,
header: {
"Content-Type": "applciation/json"
},
method: "POST",
success: (res) => {
wx.hideLoading()
callBack(true, res.data)
},
fail: (err) => {
wx.hideLoading()
callBack(false, err)
}
})
};
//上传文件
const uploadFile = (paths, callBack) => {
let gUrl = getApp().globalUrl;
showLoading('正在上传', true)
for (var i = 0; i < paths.length; i++) {
wx.uploadFile({
url: gUrl.baseUrl + gUrl.uploadImg,
filePath: paths[i],
name: 'file',
success: (res) => {
var data = JSON.parse(res.data);
if (data.suc == 'y') {
callBack({ imgSrc: data.data.file.url, image_id: data.data.file.image_id })
} else {
showModal(data.msg);
}
},
fail: () => {
showModal("上传图片失败!");
},
complete: () => {
wx.hideLoading();
}
})
}
};
const chooseImg = (num, callback) => {
wx.chooseImage({
count: num,
success: (res) => {
var arr = [];
uploadFile(res.tempFilePaths, (rtn) => {
arr.push(rtn)
if (arr.length === res.tempFilePaths.length) {
callback(arr)
}
})
}
})
};
module.exports = {
formatTime: formatTime
getData: getData,
postData: postData,
chooseImg: chooseImg
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment