XMPP 按最新消息查询存档

XMPP query archive by latest messages

我正在阅读 http://xmpp.org/extensions/xep-0313.html 以查询 Ejabberd 以获取某个用户存档的消息。

这是我要发送的xml:

<iq type='get' id='get_archive_user1'>
 <query xmlns='urn:xmpp:mam:tmp'>
  <with>user1@localhost</with>
  <set xmlns='http://jabber.org/protocol/rsm'>
   <max>20</max>
  </set>
 </query>
</iq>

我正确接收了前 20 条消息。要再次请求,我将添加标签:

<after>(id in element "Last" from last request)</after>

这也很好用。我需要的是接收最后 20 条消息,而不是前 20 条消息。我怎样才能做到这一点?

您应该添加一个空的 <before/> 元素:

<iq type='get' id='get_archive_user1'>
    <query xmlns='urn:xmpp:mam:tmp'>
        <with>user1@localhost</with>
        <set xmlns='http://jabber.org/protocol/rsm'>
            <max>20</max>
            <before/>
        </set>
    </query>
</iq>

参见here

XEP-0313 Message Archive Management rely on XEP-0059 Result Set Management 用于分页。

RSM 规范说明how to get the last page in a Result Set:

The requesting entity MAY ask for the last page in a result set by including in its request an empty <before/> element, and the maximum number of items to return.

这意味着您需要在结果集查询中添加一个空的 <before/> 元素。

这里是一个基于 XEP-0313 版本 0.4 的示例,说明如何获取与给定用户的对话中的最后 20 条消息。查询限制由参数 max 定义(它定义了页面的大小)。

<iq type='set' id='q29302'>
  <query xmlns='urn:xmpp:mam:0'>
    <x xmlns='jabber:x:data' type='submit'>
      <field var='FORM_TYPE' type='hidden'>
        <value>urn:xmpp:mam:0</value>
      </field>
      <field var='with'>
        <value>juliet@capulet.lit</value>
      </field>
    </x>
    <set xmlns='http://jabber.org/protocol/rsm'>
     <max>20</max>
     <before/>
    </set>
  </query>
</iq>

想用 Smack 获取这个的人可以使用下面的代码

 public MamManager.MamQueryResult getArchivedMessages(String jid, int maxResults) {

        MamManager mamManager = MamManager.getInstanceFor(connection);
        try {
            DataForm form = new DataForm(DataForm.Type.submit);
            FormField field = new FormField(FormField.FORM_TYPE);
            field.setType(FormField.Type.hidden);
            field.addValue(MamElements.NAMESPACE);
            form.addField(field);

            FormField formField = new FormField("with");
            formField.addValue(jid);
            form.addField(formField);

            // "" empty string for before
            RSMSet rsmSet = new RSMSet(maxResults, "", RSMSet.PageDirection.before);
            MamManager.MamQueryResult mamQueryResult = mamManager.page(form, rsmSet);

            return mamQueryResult;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }