Stanza.io插件XEP-0012:Last Activity

时间:2016-12-15 05:08:27

标签: xmpp ejabberd stanza.io

默认情况下,我想实施XEP-0012,Stanza.io不支持。

我正在关注如何从其文档中创建插件,但它无法正常工作。

继承我的代码(last.js):

'use strict';

module.exports = function (client) {

    client.disco.addFeature('jabber:iq:last');

    client.on('jabber:iq:last', function (iq) {
        client.sendIq(iq.resultReply({
            last: new Date().getTime()
        }));
    });

    client.getLastActivity = function (jid, cb) {
        return this.sendIq({
            to: jid,
            type: 'get',
            last: true
        }, cb);
    };

};

然后我用它:client.use(require('last'))

但是当我调用该函数时,它返回错误bad request <bad-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error>

我错过了什么?

感谢

2 个答案:

答案 0 :(得分:1)

我们基本上需要创建一个自定义节并将其发送为 iq

this.client.use(this.setCustomMessage.bind(this));
setCustomMessage(client, stanzas) {
const lastActivity = stanzas.define({
    name: 'lastActivity',
    element: 'query',
    namespace: 'jabber:iq:last',
    fields: {
    seconds: stanzas.utils.attribute('seconds')
    }
});
stanzas.withIQ(iq => {
            stanzas.extend(iq, lastActivity);
        });
}

并获取具有 id

的jid的用户的lastActivity
getLastActivity(userId, cb) {
        return this.client.sendIq({
            to: 'userId',
            type: 'get',
            id: 'last',
            query: true
        }, cb);
    }
}

您可以通过两种方式获取上次活动的结果: 要么得到承诺的答复

this.getLastActivity(userId).then(data => {
    if (data && data.query && data.query.seconds) {
    // Math.round(new Date())-(parseInt(data.query.seconds, 10)*1000) 
       will give last activity 
    }
});

client.on('iq', data => {
    if (data.query && data.query.seconds) {
    // Math.round(new Date())-(parseInt(data.query.seconds, 10)*1000) 
       will give last activity 
    }
});

答案 1 :(得分:1)

module.exports = function (client, stanzas) {

// 1. Create and register our custom `mystanza` stanza type

const helpers = stanzas.utils;

const IqLastActivity = stanzas.define({
    name: 'query',
    element: 'query',
    namespace: 'jabber:iq:last',
    fields: {
        seconds: helpers.attribute('seconds')
    }
});

stanzas.withIq((Iq) => {
    stanzas.extend(Iq, IqLastActivity);
});

// eslint-disable-next-line no-param-reassign
client.lastActivityByIq = (data) => {
    client.sendIq(data);
};
client.on('iq', (iq) => {
    if (iq.query) {
        client.emit('iq:last', iq);
    }
});

client.on('iq:last', (iq) => {
       console.log('iq:last', iq);
});
};

将此代码添加到您的客户端文件

从'./PathToFile/iqLastActivity'导入IqLastActivity;

client.use(IqLastActivity);