我正在将ejabberd18.09用于IM应用程序。该应用程序具有一些功能,无需为ejabberd(xmpp)消息添加扩展名。
我在offline_message_hook上创建了一个自定义模块,以捕获脱机消息并将其发送到我自己的url进行进一步处理。
要发送到ejabberd的邮件,根据以下邮件类型的不同,情况也不同
如果我要发送照片,则消息如下
<message xmlns="jabber:client" xml:lang="en" to="someuserjid2" from="{someuserjid}" type="chat" id="mP8tO-8">
<mtype xmlns="urn:xmpp:mtype" value="media" />
<url xmlns="urn:xmpp:url" id="myId" mediaType="photo" link="myphotourl.com" />
<body>thumbnail string</body>
</message>
发送文本时
<message xmlns="jabber:client" xml:lang="en" to="someuserjid2" from="{someuserjid}" type="chat" id="mP8tO-8">
<mtype xmlns="urn:xmpp:mtype" value="text" />
<body>Hi John</body>
</message>
发送位置信息
<message xmlns="jabber:client" xml:lang="en" to="someuserjid2" from="{someuserjid}" type="chat" id="mP8tO-8">
<mtype xmlns="urn:xmpp:mtype" value="location" />
<location xmlns="urn:xmpp:geo" lat="1.2" lng="2.2 " />
<body>location thumbnailstring</body>
</message>
我使用.erl代码读取正文和消息ID,如下所示
create_message(_From, _To, Packet) when (Packet#message.type == chat) and (Packet#message.body /= []) ->
Body = fxml:get_path_s(Packet, [{elem, list_to_binary("body")}, cdata]),
MessageId = fxml:get_tag_attr_s(list_to_binary("id"), Packet),
post_offline_message(_From, _To, Body, MessageId),
ok.
我想要的是如何(以erlang格式)读取 mtype 标记的 value 属性,以在(media,location,测试)值,以便我可以分别处理每条消息?
答案 0 :(得分:2)
您可以将参数列表中的attr
传递给fxml:get_path_s
,以挑选出某个元素的属性值:
case fxml:get_path_s(Packet, [{elem, <<"mtype">>}, {attr, <<"value">>}]) of
<<"media">> ->
%% handle media...
<<"location">> ->
%% handle location...
<<"">> ->
%% no mtype element, or missing value attribute!
%% let's handle that case as well
end
另一种想法:您实际上是否需要<mtype>
元素?看来您只需要检查<location>
或<url>
元素的存在即可。您可以这样:
case fxml:get_subtag(Packet, <<"location">>) of
false ->
%% No location. Try url
case fxml:get_subtag(Packet, <<"url">>) of
false ->
%% Neither location nor url
%% Handle this case somehow...
Url ->
%% Do something with Url...
end
Location ->
%% Do something with Location...
end
代码有点混乱,因为我们需要嵌套case
表达式,这与以前的版本中只检查单个表达式的值不同。您可以做的一件事是编写一个辅助函数,依次尝试每个元素:
find_one_of(Packet, []) ->
not_found;
find_one_of(Packet, [ElementName | Rest]) ->
case fxml:get_subtag(Packet, ElementName) of
false ->
find_one_of(Packet, Rest);
Element ->
{ElementName, Element}
end.
然后像这样调用它:
case find_one_of(Packet, [<<"location">>, <<"url">>]) of
{<<"location">>, Location} ->
%% Do something with Location...
{<<"url">>, Url} ->
%% Do something with Url...
not_found ->
%% Neither location nor url
end