【问题标题】:Strophe.js - How to get a group of rosters with its members?Strophe.js - 如何获得一组名册及其成员?
【发布时间】:2018-01-24 19:24:42
【问题描述】:

当使用这个 Strophe 命令时:

var iq = $iq({type: 'get'}).c('query', {xmlns: 'jabber:iq:roster'}); 
connection.sendIQ(iq)

我得到这个作为成功回调:

<iq xmlns="jabber:client" xml:lang="pt-br" to="user01@localhost/100164477219111523302818" from="user01@localhost" type="result" id="82480785-c170-48d1-a180-bcadbff957d2:sendIQ">
  <query xmlns="jabber:iq:roster">
    <item subscription="both" jid="user02@localhost">
      <group>Roster01</group>
      <group>Roster02</group>
    </item>
    <item subscription="both" jid="admin@localhost">
      <group>Roster01</group>
      <group>Roster02</group>
    </item>
    <item subscription="both" jid="grupo02@conference.localhost">
      <group>Roster02</group>
    </item>
    <item subscription="both" jid="grupo01@conference.localhost">
      <group>Roster01</group>
    </item>
  </query>
</iq>

我想知道是否有某种方法可以让这个回调按组及其成员分组。如果没有,我怎么能用 Javascript 做到这一点。示例:

  • 名册 01 有 admin、user02 和 grupo01
  • Roster 02 有 admin、user02 和 grupo02

我使用 ejabberd 作为 XMPP 服务器,使用 Ionic 3 作为客户端。

【问题讨论】:

    标签: xmpp ejabberd strophe


    【解决方案1】:

    我建议使用strophejs-plugin-roster 让事情变得更容易:

    // connect Strophe
    connection = new Strophe.Connection(url);
    connection.connect(my_jid, my_pwd, onConnect);
    
    ...
    
    function onConnect(status) {
        if (status == Strophe.Status.CONNECTED) {
            ...
    
            // pass connection to roster plugin
            connection.roster.init(connection);
        }
    }
    

    这是一个通过插件获取名单的函数,结果是一个包含对象的 JS 数组(而不是 XML...):

    function getRoster() {
        connection.roster.get(function (roster) {
            console.log('   >roster:', roster);
            for (var i in roster) {
                console.log('   >buddy '+i+':');
                console.log('       >'+roster[i].name+" ("+roster[i].jid+' -->'+roster[i].subscription);
                console.log('       >', roster[i].groups);
            }
            // get buddies belonging to group1 and group2 (see below)
            console.log('   >roster-group1:', getRosterGroup(roster, 'group1'));
            console.log('   >roster-group2:', getRosterGroup(roster, 'group2'));
        });
    }
    

    下面的功能按组过滤好友:

    function getRosterGroup(roster, group) {
        var reduced = roster.reduce(function(filtered, item) {
            if (item.groups.indexOf(group)!==-1) {
                filtered.push(item);
            }
            return filtered;
        }, []);
        return reduced;
    }
    

    这是一个正常工作的 Plunker:http://plnkr.co/edit/XloJABSGHZvLTp3Js2KI?p=preview

    【讨论】:

    • 谢谢,很棒的 Plunker!
    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多