uniapp 链接openfire
import xmldom from './x2j/xmldom/dom-parser.js'
var DOMParser = xmldom.DOMParser;
let document = new DOMParser().parseFromString("<?xml version='1.0'?>\n", 'text/xml');
import X2JS from './x2j/x2js/we-x2js.js'
import XML from './ObjTree.js'
import {btoa} from './base64.min.js'
//消息服务地址
const XMPPSERVER = "wss://域名地址:7443/ws";
//消息域名
const XMPPDOMAIN = "域名";
const XMPPDOMAINSUFFIX = "@域名";
//房间URL
const ROOMURL = "conference.域名";
const ROOMURLSUFFIX = "@conference.域名";
//查询服务
const SEARCHURL = "search.域名";
let AppIM ={};
function HHJYIM(){
if (!(this instanceof HHJYIM)) {
return new HHJYIM();
}
}
// //构造函数
function HHJYIMConnection(options) {
if (!(this instanceof HHJYIMConnection)) {
return new HHJYIMConnection(options);
}
options = options || {};
this.url = XMPPSERVER;
this.domain = XMPPDOMAIN;
console.log(11);
};
//socket 连接对象
let socketTask = null;
//链接ID
let connectionID = null;
//链接用户名
let username=null;
//链接密码
let password=null;
//是否已经登录
let isLogin = false;
//链接成功回调函数
let OnConnectionCallback=null;
//全局消息监听
let GlobalMessageCallBack = null;
HHJYIMConnection.prototype = {
handlers:[],
connected:false,
//连接方法
Connection : function (options) {
console.log('连接方法-1111');
username = options.UserName;
password = options.UserPassword;
//this.service = service;
this.options = options || {};
this.jid = "";
HHJYIMConnection.prototype.handlers = [];
HHJYIMConnection.prototype.connected = false;
this.maxRetries = 5;
socketTask = uni.connectSocket({
url: XMPPSERVER,
header: {'content-type': 'application/json'},
protocols: ['xmpp'],
method: 'GET',
})
uni.onSocketOpen(function (res) {
console.log('onOpen', res);
_webSocketOpened(options);
});
OnConnectionCallback = options.OnConnection;
uni.onSocketMessage(function (res) {
console.log("uni.onSocketMessage",res);
onMessage(res,options);
});
},
//设置消息链接的回调函数
AddHandlers :function (options){
if(HHJYIMConnection.prototype.handlers.length > 0){
var repeat = HHJYIMConnection.prototype.handlers.filter(item => item.NS ==options.NS && item.Name==options.Name && item.Type==options.Type && item.ID==options.ID && item.From==options.From && item.IsHasNode==options.IsHasNode)
if(repeat.length<=0){
HHJYIMConnection.prototype.handlers.push(options);
}
}else{
HHJYIMConnection.prototype.handlers.push(options);
}
console.log("设置消息链接的回调函数",HHJYIMConnection.prototype.handlers)
},
//删除对应的回调函数
RemoveHandlers : function (options){
if(HHJYIMConnection.prototype.handlers.length > 0){
for(var index=0 ;index<HHJYIMConnection.prototype.handlers.length;index++){
var item= HHJYIMConnection.prototype.handlers[index];
if(item.NS ==options.NS && item.Name==options.Name && item.Type==options.Type && item.ID==options.ID && item.From==options.From && item.IsHasNode==options.IsHasNode){
HHJYIMConnection.prototype.handlers.splice(index,1);
}
}
}
console.log("删除对应的回调函数",HHJYIMConnection.prototype.handlers)
},
//获取我的好友列表
GetMyFriends : function (options){
var hhjyim = HHJYIM.Connection.prototype;
myFriend = hhjyim.$iq({
from: options.JID,
type: 'get',
id: "GetMyFriends"
}).c('query', { xmlns: HHJYIM.prototype.NS.ROSTER });
uni.sendSocketMessage({
data: myFriend.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//设置在线状态
SettingOnline : function (options){
var setOnLine = null;
var hhjyim = HHJYIM.prototype;
if (options.Type == "chat"){
setOnLine = hhjyim.$pres(
{ "id": "OnlineSetting" }
).c("status").t("在线")
.up().c("priority").t("1");
}
if (options.Type == "away"){
setOnLine = hhjyim.$pres(
{ "id": "OnlineSetting" })
.c("status").t("离开")
.up().c("priority").t("0")
.up().c("show").t("away");
}
if (options.Type == "dnd") {
setOnLine = hhjyim.$pres(
{ "id": "OnlineSetting" })
.c("status").t("忙碌")
.up().c("priority").t("0")
.up().c("show").t("dnd");
}
uni.sendSocketMessage({
data: setOnLine.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//查找好友
SearchFriends : function (options) {
var hhjyim = HHJYIM.prototype;
var searchFriends = hhjyim.$iq({
to: SEARCHURL,
type: 'set',
id: "SearchFriends"
}).c('query', { xmlns: HHJYIM.prototype.NS.SEARCH })
.c("x", { "xmlns": HHJYIM.prototype.NS.DATA, "type": "submit" })
.c("field", { "var": "FORM_TYPE", "type": "hidden" })
.c("value").t(HHJYIM.prototype.NS.SEARCH)
.up().up().c("field", { "var": "search", "type": "text-single" })
.c("value").t(options.FriendsName)
.up().up().c("field", { "var": "Username", "type": "boolean" })
.c("value").t("1")
.up().up().c("field", { "var": "Name", "type": "boolean" })
.c("value").t("1")
.up().up().c("field", { "var": "Email", "type": "boolean" })
.c("value").t("1");
uni.sendSocketMessage({
data: searchFriends.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//添加好友
AddFriend : function (options) {
var hhjyim = HHJYIM.prototype;
var addFriend = hhjyim.$iq({
type: 'set',
id: "SetFriendToGroup"
}).c('query', { xmlns: 'jabber:iq:roster' })
.c("item", { "jid": options.JID, "name": options.FriendName })
.c("group").t("组名称");
uni.sendSocketMessage({
data: addFriend.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//同意好友
AgreeFriend : function (options){
var hhjyim = HHJYIM.prototype;
var agreeFriends = hhjyim.$pres({ to: options.MessageContext, "type": "subscribed" });
uni.sendSocketMessage({
data: agreeFriends.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//不同意好友请求
DisagreeFriend : function (options){
var hhjyim = HHJYIM.prototype;
var disAgreeFriends = hhjyim.$pres({ to: options.MessageContext, "type": "unsubscribed" });
uni.sendSocketMessage({
data: disAgreeFriends.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//删除好友
RemoveFriend : function (options){
var hhjyim = HHJYIM.prototype;
var removeFriend = hhjyim.$iq({
from: options.Jid,
type: 'set',
id: "RemoveFriend"
}).c('query', { xmlns: HHJYIM.prototype.NS.ROSTER })
.c("item", { "jid": options.Jid, "name": options.UserName, "subscription": "remove" });
uni.sendSocketMessage({
data: removeFriend.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//销毁群组
DestroyingRoom : function (jsonPar) {
var hhjyim = HHJYIM.prototype;
var destoryRoom = $iq({
"to": jsonPar.RoomJID ,
"type": "set",
"id": "DestroyingRoom",
"from": jsonPar.UserName
}).c("query", { 'xmlns': 'http://jabber.org/protocol/muc#owner' })
.c("destroy", { "jid": jsonPar.RoomJID })
.c("reason").t(jsonPar.Reason);
uni.sendSocketMessage({
data: destoryRoom.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//离开房间
LeaveRoom : function (options){
var hhjyim = HHJYIM.prototype;
setOnLine = hhjyim.$pres({ to: options.RoomJID + "/" + options.UserName, "type": "unavailable" });
uni.sendSocketMessage({
data: setOnLine.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//邀请进入房间
InviteUserToRoom : function (options){
var hhjyim = HHJYIM.prototype;
var inviteUser = hhjyim.$msg({
to: options.RoomJID
}).c("x", { "xmlns": HHJYIM.prototype.NS.MUC_USER })
.c("invite", { "to": options.InviteUserJID })
.c("reason").t(options.Reason);
uni.sendSocketMessage({
data: inviteUser.tree().toString() ,
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//创建房间
CreateRoom : function (options){
var hhjyim = HHJYIM.prototype;
//默认属性
var defaults = {
IsPerpetual: "1",
PublicRoom: "1",
RoomNumberCount: "500",
IsInvitation: "1",
RoomName: "默认房间",
RoomDescription: "默认房间",
IsSaveMessage: "1"
};
options = Object.assign(defaults, options);
//发送创建房间请求
var fromUser = options.FromUser + XMPPDOMAINSUFFIX;
var toRoom = options.RoomName + ROOMURLSUFFIX + '/' + options.FromUser;
var roomPresen = hhjyim.$pres({
from: fromUser,
to: toRoom
}).c("x", { "xmlns": HHJYIM.prototype.NS.MUC });
uni.sendSocketMessage({ data: roomPresen.tree().toString() });
//查询房间配置
var queryRoom = hhjyim.$iq({
from: fromUser,
id: 'queryRoomInfo',
to: toRoom,
type: 'get'
}).c("query", {
xmlns: HHJYIM.prototype.NS.MUC_OWNER
});
uni.sendSocketMessage({ data: queryRoom.tree().toString()});
var setRoomIQ = hhjyim.$iq({
from: fromUser,
id: 'SetRoomInfo',
to: toRoom,
type: 'set'
}).c("query", {
xmlns: HHJYIM.prototype.NS.MUC_OWNER
});
setRoomIQ.c("x", {
xmlns: HHJYIM.prototype.NS.DATA,
type: "submit"
});
setRoomIQ.c('field', { 'var': 'muc#roomconfig_persistentroom' }).c('value').t(options.IsPerpetual).up().up();//是否永久
setRoomIQ.c('field', { 'var': 'muc#roomconfig_publicroom' }).c('value').t(options.PublicRoom).up().up();//是否显示房间
setRoomIQ.c('field', { 'var': 'muc#roomconfig_maxusers' }).c('value').t(options.RoomNumberCount).up().up();//最大房客数
setRoomIQ.c('field', { 'var': 'muc#roomconfig_allowinvites' }).c('value').t(options.IsInvitation).up().up();//允许成员邀请其他人
setRoomIQ.c('field', { 'var': 'muc#roomconfig_roomname' }).c('value').t(options.RoomName).up().up();//设置房间名称
setRoomIQ.c('field', { 'var': 'muc#roomconfig_roomdesc' }).c('value').t(options.RoomDescription).up().up();//设置房间描述
setRoomIQ.c('field', { 'var': 'muc#roomconfig_enablelogging' }).c('value').t(options.IsSaveMessage).up().up(); //是否保存消息履历
setRoomIQ.c("field", { 'var': 'muc#roomconfig_presencebroadcast' }).c("value").t("participant").up().up();
uni.sendSocketMessage({
data: setRoomIQ.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//获取我的群组列表
GetMyRooms : function (options) {
var hhjyim = HHJYIM.prototype;
var getRooms = hhjyim.$iq({
from: options.JID,
to: options.RoomUrl,
type: 'get',
id: "GetMyRooms"
}).c("query", { "xmlns": HHJYIM.prototype.NS.DISCO_ITEMS });
uni.sendSocketMessage({
data: getRooms.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//加入房间
JoinRoom : function (options){
var hhjyim = HHJYIM.prototype;
// var pres = hhjyim.$pres({
// to: options.RoomJID + ROOMURLSUFFIX + '/' + options.UserName
// }).c("x", { xmlns: HHJYIM.prototype.NS.MUC });
// uni.sendSocketMessage({ data: pres.tree().toString() });
//设置权限
var setRole = hhjyim.$iq({
to: options.RoomJID+ ROOMURLSUFFIX ,
type: "set"
}).c('query', { xmlns: HHJYIM.prototype.NS.MUC + "#admin" })
.c('item', {
jid: options.UserName + XMPPDOMAINSUFFIX,
affiliation: "participant"
});
uni.sendSocketMessage({
data: setRole.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//群组踢人
OutCastRoom : function (options){
var hhjyim = HHJYIM.prototype;
var outcast = hhjyim.$iq({
to: options.RoomJID,
type: "set",
}).c('query', {xmlns: HHJYIM.prototype.NS.MUC + "#admin"})
.c('item', {jid: options.UserName, affiliation: "outcast"});
uni.sendSocketMessage({
data: outcast.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//设置为管理员
SetUserAdmin:function (options){
var hhjyim = HHJYIM.prototype;
var adminUser = hhjyim.$iq({
to: options.RoomJID,
type: "set",
}).c('query', {xmlns: HHJYIM.prototype.NS.MUC + "#admin"})
.c('item', {jid: options.UserName, affiliation: "admin"});
uni.sendSocketMessage({
data: adminUser.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//ping设置
SendPingfunction :function (options) {
var hhjyim = HHJYIM.prototype;
var ping = hhjyim.$iq({
to: XMPPDOMAIN,
type: "get",
id: "ping"
}).c("ping", { xmlns: "urn:xmpp:ping" });
uni.sendSocketMessage({
data: ping.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//关闭连接
Disconnecting : function (options){
var hhjyim = HHJYIM.prototype;
var presence = hhjyim.$pres({ "type":"unavailable" });
console.log(presence.toString());
uni.sendSocketMessage({ data: presence.tree().toString() });
//发送stream
var stream = {
"stream:stream":{}
}
var streamXml = HHJYIM.prototype.JsonToXML(stream);
uni.sendSocketMessage({
data: streamXml ,
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
},
//发送消息
SendMessage :function(options){
var hhjyim = HHJYIM.prototype;
var setOnLine = hhjyim.$pres(
{ "id": "OnlineSetting" }
).c("status").t("在线")
.up().c("priority").t("1");
uni.sendSocketMessage({ data: setOnLine.tree().toString() });
if(options.Type == "chat"){
var toUser = options.ToUser + XMPPDOMAINSUFFIX;
var fromUser = options.FromUser + XMPPDOMAINSUFFIX;
var messageInfo = hhjyim.$msg({
to: toUser,
from: fromUser,
type: options.Type,
file: options.CustomType == null ? "" : options.CustomType
}).c("body").t(""+options.Message);
console.log("单人发送消息",messageInfo.tree().toString());
uni.sendSocketMessage({
data: messageInfo.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
}else{
var toUser = options.ToUser ;
var fromUser = options.FromUser + XMPPDOMAINSUFFIX;
var messageInfo = hhjyim.$msg({
to: toUser +ROOMURLSUFFIX,
from: fromUser,
type: options.Type,
file: options.CustomType == null ? "" : options.CustomType
}).c("body").t(""+options.Message);
console.log("群组发送消息",messageInfo.tree().toString());
uni.sendSocketMessage({
data: messageInfo.tree().toString(),
success:function(){
options.Success();
},
fail:function(){
options.fail();
},
complete:function(){
options.complete()
}
});
}
}
}
HHJYIM.prototype = {
_xmlGenerator: null,
//创建对应的节点
$build: function (name, attrs) { return new HHJYIM.Builder(name, attrs); },
//形成msg节点
$msg: function (attrs) { return new HHJYIM.Builder("message", attrs);},
//形成iq节点
$iq: function (attrs) { return new HHJYIM.Builder("iq", attrs);},
//形成presence 节点
$pres: function (attrs) { return new HHJYIM.Builder("presence", attrs)},
//打开
$open: function (attrs) { return new HHJYIM.Builder("open", attrs)},
//对应对应的命名空间
NS:{
HTTPBIND: "http://jabber.org/protocol/httpbind",
BOSH: "urn:xmpp:xbosh",
CLIENT: "jabber:client",
AUTH: "jabber:iq:auth",
ROSTER: "jabber:iq:roster",
PROFILE: "jabber:iq:profile",
SEARCH: "jabber:iq:search",
DATA: "jabber:x:data",
DISCO_INFO: "http://jabber.org/protocol/disco#info",
DISCO_ITEMS: "http://jabber.org/protocol/disco#items",
MUC: "http://jabber.org/protocol/muc",
MUC_OWNER: "http://jabber.org/protocol/muc#owner",
MUC_USER: "http://jabber.org/protocol/muc#user",
SASL: "urn:ietf:params:xml:ns:xmpp-sasl",
STREAM: "http://etherx.jabber.org/streams",
BIND: "urn:ietf:params:xml:ns:xmpp-bind",
SESSION: "urn:ietf:params:xml:ns:xmpp-session",
VERSION: "jabber:iq:version",
REGISTER: "jabber:iq:register",
STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas",
FRAMING: "urn:ietf:params:xml:ns:xmpp-framing",
XMLLANG: "zh"
},
Status: {
ERROR: 0,
CONNECTING: 1,
CONNFAIL: 2,
AUTHENTICATING: 3,
AUTHFAIL: 4,
CONNECTED: 5,
DISCONNECTED: 6,
DISCONNECTING: 7
},
ElementType: {
NORMAL: 1,
TEXT: 3
},
//超时时间
TIMEOUT: 70,
//二次超时
SECONDARY_TIMEOUT: 7,
//添加命名空间
addNamespace: function (name, value) {
HHJYIM.NS[name] = value;
},
//判断节点是否相同
isTagEqual: function (data, name) {
return data[name] ;
},
//JSON 格式化XML
JsonToXML:function (jsonStr) {
var xotree = new XML.ObjTree();
var xml = xotree.writeXML(jsonStr);
return xml;
},
//xml 转JSON
XMLToJson:function(xml){
var x2js = new X2JS();
var json = x2js.xml2js(xml);
return json;
},
//xml节点形成
xmlElement: function (name) {
if (!name) { return null; }
var node = null;
if (!HHJYIM._xmlGenerator) {
HHJYIM.prototype._xmlGenerator = HHJYIM.prototype._makeGenerator();
}
node = HHJYIM.prototype._xmlGenerator.createElement(name);
var a, i, k;
for (a = 1; a < arguments.length; a++) {
if (!arguments[a]) { continue; }
if (typeof (arguments[a]) == "string" ||
typeof (arguments[a]) == "number") {
node.appendChild(HHJYIM.prototype.xmlTextNode(arguments[a]));
} else if (typeof (arguments[a]) == "object" &&
typeof (arguments[a]['sort']) == "function") {
for (i = 0; i < arguments[a].length; i++) {
if (typeof (arguments[a][i]) == "object" &&
typeof (arguments[a][i]['sort']) == "function") {
node.setAttribute(arguments[a][i][0],
arguments[a][i][1]);
}
}
} else if (typeof (arguments[a]) == "object") {
for (k in arguments[a]) {
if (arguments[a].hasOwnProperty(k)) {
node.setAttribute(k, arguments[a][k]);
}
}
}
}
return node;
},
//xml形成器
_makeGenerator: function () {
var doc;
if (document.implementation.createDocument === undefined ||
document.implementation.createDocument && document.documentMode && document.documentMode < 10) {
doc = this._getIEXmlDom();
doc.appendChild(doc.createElement('HHJYIM'));
} else {
doc = document.implementation.createDocument('jabber:client', 'HHJYIM', null);
}
return doc;
},
//序列化xml
serialize: function (elem) {
var result;
if (!elem) return null;
if (typeof (elem["tree"]) === "function") {
elem = elem.tree();
}
var nodeName = elem.nodeName;
var i, child;
if (elem.getAttribute("_realname")) {
nodeName = elem.getAttribute("_realname");
}
result = "<" + nodeName;
for (i = 0; i < elem.attributes.length; i++) {
if (elem.attributes[i].nodeName != "_realname") {
result += " " + elem.attributes[i].nodeName.toLowerCase() +
"='" + elem.attributes[i].value
.replace("'", "'").replace("&", "&") + "'";
}
}
if (elem.childNodes.length > 0) {
result += ">";
for (i = 0; i < elem.childNodes.length; i++) {
child = elem.childNodes[i];
if (child.nodeType == HHJYIM.prototype.ElementType.NORMAL) {
result += HHJYIM.serialize(child);
} else if (child.nodeType == HHJYIM.prototype.ElementType.TEXT) {
result += child.nodeValue;
}
}
result += "</" + nodeName + ">";
} else {
result += "/>";
}
return result;
},
//创建一个xml text Node
xmlTextNode: function (text) {
text = HHJYIM.prototype.xmlescape(text);
if (!HHJYIM.prototype._xmlGenerator) {
HHJYIM.prototype._xmlGenerator = HHJYIM.prototype._makeGenerator();
}
return HHJYIM.prototype._xmlGenerator.createTextNode(text);
},
//取消无效的特殊字符
xmlescape: function (text) {
text = text.replace(/\&/g, "&");
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
return text;
},
};
//节点创建类
HHJYIM.Builder = function (name, attrs){
if (name == "presence" || name == "message" || name == "iq") {
if (attrs && !attrs.xmlns)
attrs.xmlns = HHJYIM.prototype.NS.CLIENT;
else if (!attrs)
attrs = { xmlns: HHJYIM.prototype.NS.CLIENT };
}
this.nodeTree = HHJYIM.prototype.xmlElement(name, attrs);
this.node = this.nodeTree;
}
HHJYIM.Builder.prototype = {
//制作一个节点树
tree: function () {
return this.nodeTree;
},
//序列化节点数为一个字符串
toString: function () {
return HHJYIM.prototype.serialize(this.nodeTree);
},
//当前节点的上级节点
up: function () {
this.node = this.node.parentNode;
return this;
},
//添加活这修改节点属性值
attrs: function (moreattrs) {
for (var k in moreattrs){
this.node.setAttribute(k, moreattrs[k]);
}
return this;
},
//当前节点下添加节点
c: function (name, attrs) {
var child = HHJYIM.prototype.xmlElement(name, attrs);
this.node.appendChild(child);
this.node = child;
return this;
},
//添加一个子节点,并是他当做现在的新节点
cnode: function (elem) {
this.node.appendChild(elem);
this.node = elem;
return this;
},
//设置节点的对应的值
t: function (text) {
var child = HHJYIM.prototype.xmlTextNode(text);
this.node.appendChild(child);
return this;
}
}
//打开连接socket
function _webSocketOpened(options) {
var hhjyim = HHJYIM.prototype;
var from = options.UserName + XMPPDOMAINSUFFIX;
var open = hhjyim.$open({
"to": XMPPDOMAIN,
"from": from,
"xmlns": HHJYIM.prototype.NS.FRAMING,
"xml:lang":HHJYIM.prototype.NS.XMLLANG,
"version": "1.0"
});
var steam= open.tree().toString();
console.log(steam);
uni.sendSocketMessage({
data: steam,
success:function(){
console.log("connwsopen");
},
fail:function(){
console.log("connwsopen");
}
});
}
// 收到消息的处理函数
function onMessage(event,options) {
var jsondata = HHJYIM.prototype.XMLToJson(event.data);
//自定义监听事件
for (let index = 0; index < HHJYIMConnection.prototype.handlers.length; index++) {
var hand = HHJYIMConnection.prototype.handlers[index];
if (customListerMatch(jsondata, hand)) {
hand.CallBack(jsondata);
}
}
//判断是否是消息节点
if (undefined != jsondata.message) {
if (undefined != jsondata.message.body) {
} else if (undefined != jsondata.message.composing) {
//对方正在输入
} else if (undefined != jsondata.message.gone) {
//对方已关闭和您的聊天
} else if (undefined != jsondata.message.file) {
//收到的文件:
} else {
console.log("其他:", jsondata.message);
}
} else if (undefined != jsondata.open) {
//记录id
connectionID = jsondata.open["_id"];
} else if (undefined != jsondata["features"]) {
if (undefined != jsondata["features"].mechanisms) {
//获取登录验证方式
socketAuth(jsondata["features"].mechanisms.mechanism[0]);
} else if (undefined != jsondata["features"].bind) {
sockeBind();
} else {
//绑定失败
}
} else if (undefined != jsondata.failure) {
//islogin = false; //TODO
console.log("登录失败,用户名或者密码错误");
} else if (undefined != jsondata.success) {
//发起新的流
newSocket();
} else if (undefined != jsondata.iq) {
if (undefined != jsondata.iq.bind) {
//获取session会话
setSession();
} else {
console.log("登录成功!");
//islogin = true; //TODO
setOnline();
//链接成功回调函数
OnConnectionCallback();
}
} else {
}
}
//设置在线状态
function setOnline(){
var hhjyim = HHJYIM.prototype;
var temp = hhjyim.$pres().c("priority").t("1");
//转化为xml
uni.sendSocketMessage({ data: temp.tree().toString() })
}
//设置Session
function setSession(){
var temp = {
"iq": {
"-xmlns": "jabber:client",
"-id": connectionID,
"-type": "set",
"session": { "-xmlns": HHJYIM.prototype.NS.SESSION }
}
};
var steam = HHJYIM.prototype.JsonToXML(temp);
uni.sendSocketMessage({ data: steam })
}
//再次握手
function newSocket(){
var hhjyim = HHJYIM.prototype;
var fromUser = username + XMPPDOMAINSUFFIX
var open = hhjyim.$open({
"xmlns": HHJYIM.prototype.NS.CLIENT,
"to": XMPPDOMAIN,
"version": "1.0",
"from": fromUser,
"xml:lang": HHJYIM.prototype.NS.XMLLANG
});
uni.sendSocketMessage({ data: open.tree().toString() });
}
//状态更改事件
function _changeConnectStatus (status, condition) {
for (var k in Strophe._connectionPlugins) {
var plugin = this[k];
if (plugin.statusChanged) {
try {
plugin.statusChanged(status, condition);
} catch (err) {
Strophe.error("" + k + " plugin caused an exception " +
"changing status: " + err);
}
}
}
if (this.connect_callback) {
try {
this.connect_callback(status, condition);
} catch (err) {
Strophe.error("User connection callback caused an " +
"exception: " + err);
}
}
}
// bind操作
function sockeBind(){
var temp = {
"iq": {
"-id": connectionID,
"-type": "set",
"bind": {
"-xmlns": HHJYIM.prototype.NS.BIND,
"resource": "MiNiProgram"
}
}
};
//转化为xml
var steam = HHJYIM.prototype.JsonToXML(temp);
uni.sendSocketMessage({ data: steam })
}
//auth 登录验证
function socketAuth(authentication){
//字符串格式是:jid+password,以\0作为分隔符
var temp = username + XMPPDOMAINSUFFIX + "\0" + password;
//Base64编码
var token = btoa(temp);
var message = {
"auth": {
"-xmlns": HHJYIM.prototype.NS.SASL,
"-mechanism": authentication,
"#text": token
}
};
uni.sendSocketMessage({
data: HHJYIM.prototype.JsonToXML(message)
})
}
//自定义监听事件匹配方法
function customListerMatch(messageJson,handler){
var nsMatch, i;
nsMatch = false;
if (!handler.Name){
return false;
}
//循环对应的消息内容匹配对应监听事件
if (!handler.NS){
nsMatch = true;
}else{
for (let key in messageJson){
if (key == handler.NS){
nsMatch = true;
}
}
if (messageJson[handler.Name]){
nsMatch = nsMatch || messageJson[handler.Name]._xmlns == handler.NS;
}
}
if (nsMatch &&
(!handler.Name || HHJYIM.prototype.isTagEqual(messageJson, handler.Name)) &&
(!handler.Type || messageJson[handler.Name]._type== handler.Type) &&
(!handler.ID || messageJson[handler.Name]._id == handler.ID) &&
(!handler.From || messageJson[handler.Name]._from == handler.From) &&
(!handler.IsHasNode || messageJson[handler.Name].hasOwnProperty(handler.IsHasNode))
) {
return true;
}
return false;
}
AppIM.HHJYIM = HHJYIM;
AppIM.HHJYIMConnection = HHJYIMConnection;
module.exports = AppIM;
以上有不懂的,或者需要指导调用的请联系我
你的支持是给我最大的动力
本文地址:https://blog.csdn.net/affordlove/article/details/107167668