Ejabberd Packet parsing using erlang -
ejabberd server receives packet this:
{xmlel,<<"message">>,[{<<"from">>,<<"user1@localhost/resource">>},{<<"to">>,<<"user2@localhost">>},{<<"xml:lang">>,<<"en">>},{<<"id">>,<<"947yw-9">>}],[{xmlcdata,<<">">>},{xmlel,<<"body">>,[],[{xmlcdata,<<"helllo wassup!">>}]}]}
i want fetch data packet. needed data : type, if body has parameter, {<<"xml:lang">>,<<"en">>}
doing following operations:
{_xmlel, type, details , _body} = packet
this provides me type : <<"message">>
or <<"iq">>
or <<"presence">>
.
to check if details has {<<"xml:lang">>,<<"en">>}
this:
has_attribute=lists:member({<<"xml:lang">>,<<"en">>},details)
is there better way this? need to
, from
attributes packet.
use combination of pattern matching in function head fold on details extract need.
the function below returns list of key-value tuples, <<"type">>
tuple artificially created list homogenous:
extract({xmlel, type, details, _}) -> [{<<"type">>,type} | lists:foldl(fun(key, acc) -> case lists:keyfind(key, 1, details) of false -> acc; pair -> [pair|acc] end end, [], [<<"from">>,<<"to">>,<<"xml:lang">>])]; extract(_) -> [].
the first clause matches {xmlel, ...}
tuple, extracting type
, details
. return value consists of list head {<<"type">>,type}
followed tail formed folding on list of keys extracted details
. second clause matches not {xmlel, ...}
tuple , returns empty list.
putting function module named z
, passing data:
1> z:extract({xzlel,<<"message">>,[{<<"from">>,<<"user1@localhost/resource">>},{<<"to">>,<<"user2@localhost">>},{<<"xml:lang">>,<<"en">>},{<<"id">>,<<"947yw-9">>}],[{xmlcdata,<<">">>},{xmlel,<<"body">>,[],[{xmlcdata,<<"helllo wassup!">>}]}]}). [{<<"type">>,<<"message">>}, {<<"xml:lang">>,<<"en">>}, {<<"to">>,<<"user2@localhost">>}, {<<"from">>,<<"user1@localhost/resource">>}]
Comments
Post a Comment