From 378b8a60c6c090fe6a93ce6b79c90114d8e3da8c Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 19 Oct 2010 17:08:59 +0200 Subject: [PATCH] add function specification, convert string() to binary(), fix pubsub.hrl (thanks to Karim Gemayel) --- src/mod_pubsub/mod_pubsub.erl | 3888 +++++++++++++++++++-------------- src/mod_pubsub/node_dag.erl | 2 +- src/mod_pubsub/node_flat.erl | 2 +- src/mod_pubsub/pubsub.hrl | 2 +- 4 files changed, 2238 insertions(+), 1656 deletions(-) diff --git a/src/mod_pubsub/mod_pubsub.erl b/src/mod_pubsub/mod_pubsub.erl index 710d00604..b02ffe3ce 100644 --- a/src/mod_pubsub/mod_pubsub.erl +++ b/src/mod_pubsub/mod_pubsub.erl @@ -126,16 +126,18 @@ -define(PLUGIN_PREFIX, "node_"). -define(TREE_PREFIX, "nodetree_"). --record(state, {server_host, - host, - access, - pep_mapping = [], - ignore_pep_from_offline = true, - last_item_cache = false, - max_items_node = ?MAXITEMS, - nodetree = ?STDTREE, - plugins = [?STDNODE]}). - +-record(state, + { + server_host :: string(), + host :: string(), + access :: atom(), + pep_mapping = [] :: [{Namespace::string(), NodeId::string()}], + ignore_pep_from_offline = true :: boolean(), + last_item_cache = false :: boolean(), + max_items_node = ?MAXITEMS :: integer(), + nodetree = 'nodetree_tree' :: atom(), + plugins = [?STDNODE] :: [Plugin::nodeType()] + }). %%==================================================================== %% API @@ -144,10 +146,25 @@ %% Function: start_link() -> {ok,Pid} | ignore | {error,Error} %% Description: Starts the server %%-------------------------------------------------------------------- +-spec(start_link/2 :: + ( + Host :: string(), + Opts :: [{Option::atom(), Value::term()}]) + -> {'ok', pid()} | 'ignore' | {'error', _} + ). + start_link(Host, Opts) -> Proc = gen_mod:get_module_proc(Host, ?PROCNAME), gen_server:start_link({local, Proc}, ?MODULE, [Host, Opts], []). + +-spec(start/2 :: + ( + Host :: string(), + Opts :: [{Option::atom(), Value::term()}]) + -> {'error',_} | {'ok','undefined' | pid()} | {'ok','undefined' | pid(),_} + ). + start(Host, Opts) -> Proc = gen_mod:get_module_proc(Host, ?PROCNAME), ChildSpec = {Proc, @@ -155,6 +172,13 @@ start(Host, Opts) -> transient, 1000, worker, [?MODULE]}, supervisor:start_child(ejabberd_sup, ChildSpec). + +-spec(stop/1 :: + ( + Host :: string()) + -> 'ok' | {'error','not_found' | 'running' | 'simple_one_for_one'} + ). + stop(Host) -> Proc = gen_mod:get_module_proc(Host, ?PROCNAME), gen_server:call(Proc, stop), @@ -171,32 +195,38 @@ stop(Host) -> %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- +-spec(init/1 :: + ( + Args :: [ServerHost::string() | [{Option::atom(), Value::term()}]]) + -> {'ok', State::#state{}} + ). + init([ServerHost, Opts]) -> ?DEBUG("pubsub init ~p ~p",[ServerHost,Opts]), Host = gen_mod:expand_host_name(ServerHost, Opts, "pubsub"), - Access = gen_mod:get_opt(access_createnode, Opts, all), - PepOffline = gen_mod:get_opt(ignore_pep_from_offline, Opts, true), - IQDisc = gen_mod:get_opt(iqdisc, Opts, one_queue), - LastItemCache = gen_mod:get_opt(last_item_cache, Opts, false), - MaxItemsNode = gen_mod:get_opt(max_items_node, Opts, ?MAXITEMS), + Access = gen_mod:get_opt('access_createnode', Opts, 'all'), + PepOffline = gen_mod:get_opt('ignore_pep_from_offline', Opts, true), + IQDisc = gen_mod:get_opt('iqdisc', Opts, 'one_queue'), + LastItemCache = gen_mod:get_opt('last_item_cache', Opts, false), + MaxItemsNode = gen_mod:get_opt('max_items_node', Opts, ?MAXITEMS), ServerHostB = list_to_binary(ServerHost), pubsub_index:init(Host, ServerHost, Opts), - ets:new(gen_mod:get_module_proc(Host, config), [set, named_table]), - ets:new(gen_mod:get_module_proc(ServerHost, config), [set, named_table]), + ets:new(gen_mod:get_module_proc(Host, 'config'), ['set', 'named_table']), + ets:new(gen_mod:get_module_proc(ServerHost, 'config'), ['set', 'named_table']), {Plugins, NodeTree, PepMapping} = init_plugins(Host, ServerHost, Opts), mnesia:create_table(pubsub_last_item, [{ram_copies, [node()]}, {attributes, record_info(fields, pubsub_last_item)}]), mod_disco:register_feature(ServerHostB, ?NS_PUBSUB_s), - ets:insert(gen_mod:get_module_proc(Host, config), {nodetree, NodeTree}), - ets:insert(gen_mod:get_module_proc(Host, config), {plugins, Plugins}), - ets:insert(gen_mod:get_module_proc(Host, config), {last_item_cache, LastItemCache}), - ets:insert(gen_mod:get_module_proc(Host, config), {max_items_node, MaxItemsNode}), - ets:insert(gen_mod:get_module_proc(ServerHost, config), {nodetree, NodeTree}), - ets:insert(gen_mod:get_module_proc(ServerHost, config), {plugins, Plugins}), - ets:insert(gen_mod:get_module_proc(ServerHost, config), {last_item_cache, LastItemCache}), - ets:insert(gen_mod:get_module_proc(ServerHost, config), {max_items_node, MaxItemsNode}), - ets:insert(gen_mod:get_module_proc(ServerHost, config), {pep_mapping, PepMapping}), - ets:insert(gen_mod:get_module_proc(ServerHost, config), {ignore_pep_from_offline, PepOffline}), - ets:insert(gen_mod:get_module_proc(ServerHost, config), {host, Host}), + ets:insert(gen_mod:get_module_proc(Host, 'config'), {'nodetree', NodeTree}), + ets:insert(gen_mod:get_module_proc(Host, 'config'), {'plugins', Plugins}), + ets:insert(gen_mod:get_module_proc(Host, 'config'), {'last_item_cache', LastItemCache}), + ets:insert(gen_mod:get_module_proc(Host, 'config'), {'max_items_node', MaxItemsNode}), + ets:insert(gen_mod:get_module_proc(ServerHost, 'config'), {'nodetree', NodeTree}), + ets:insert(gen_mod:get_module_proc(ServerHost, 'config'), {'plugins', Plugins}), + ets:insert(gen_mod:get_module_proc(ServerHost, 'config'), {'last_item_cache', LastItemCache}), + ets:insert(gen_mod:get_module_proc(ServerHost, 'config'), {'max_items_node', MaxItemsNode}), + ets:insert(gen_mod:get_module_proc(ServerHost, 'config'), {'pep_mapping', PepMapping}), + ets:insert(gen_mod:get_module_proc(ServerHost, 'config'), {'ignore_pep_from_offline', PepOffline}), + ets:insert(gen_mod:get_module_proc(ServerHost, 'config'), {'host', Host}), ejabberd_hooks:add(sm_remove_connection_hook, ServerHostB, ?MODULE, on_user_offline, 75), ejabberd_hooks:add(disco_local_identity, ServerHostB, ?MODULE, disco_local_identity, 75), ejabberd_hooks:add(disco_local_features, ServerHostB, ?MODULE, disco_local_features, 75), @@ -222,17 +252,25 @@ init([ServerHost, Opts]) -> update_state_database(Host, ServerHost), init_nodes(Host, ServerHost, NodeTree, Plugins), State = #state{host = Host, - server_host = ServerHost, - access = Access, - pep_mapping = PepMapping, - ignore_pep_from_offline = PepOffline, - last_item_cache = LastItemCache, - max_items_node = MaxItemsNode, - nodetree = NodeTree, - plugins = Plugins}, + server_host = ServerHost, + access = Access, + pep_mapping = PepMapping, + ignore_pep_from_offline = PepOffline, + last_item_cache = LastItemCache, + max_items_node = MaxItemsNode, + nodetree = NodeTree, + plugins = Plugins}, init_send_loop(ServerHost, State), {ok, State}. + +-spec(init_send_loop/2 :: + ( + ServerHost :: string(), + State :: #state{}) + -> pid() + ). + init_send_loop(ServerHost, State) -> Proc = gen_mod:get_module_proc(ServerHost, ?LOOPNAME), SendLoop = spawn(?MODULE, send_loop, [State]), @@ -252,6 +290,16 @@ init_send_loop(ServerHost, State) -> %%

The modules are initialized in alphetical order and the list is checked %% and sorted to ensure that each module is initialized only once.

%%

See {@link node_flat:init/1} for an example implementation.

+-spec(init_plugins/3 :: + ( + Host :: string(), + ServerHost :: string(), + Opts :: [{Option::atom(), Value::term()}]) + -> {Plugins :: [Plugin::nodeType()], + TreePlugin :: atom(), + PepMapping :: [{Namespace::string(), NodeId::string()}]} + ). + init_plugins(Host, ServerHost, Opts) -> TreePlugin = list_to_atom(?TREE_PREFIX ++ gen_mod:get_opt(nodetree, Opts, ?STDTREE)), @@ -267,6 +315,16 @@ init_plugins(Host, ServerHost, Opts) -> end, Plugins), {Plugins, TreePlugin, PepMapping}. + +-spec(terminate_plugins/4 :: + ( + Host :: string(), + ServerHost :: string(), + Plugins :: [Plugin::nodeType()], + TreePlugin :: atom()) + -> 'ok' + ). + terminate_plugins(Host, ServerHost, Plugins, TreePlugin) -> lists:foreach(fun(Name) -> ?DEBUG("** terminate ~s plugin",[Name]), @@ -276,16 +334,34 @@ terminate_plugins(Host, ServerHost, Plugins, TreePlugin) -> TreePlugin:terminate(Host, ServerHost), ok. + +-spec(init_nodes/4 :: + ( + Host :: string(), + ServerHost :: string(), + NodeTree :: atom(), + Plugins :: [Plugin::nodeType()]) + -> 'ok' + ). + init_nodes(Host, ServerHost, _NodeTree, Plugins) -> %% TODO, this call should be done plugin side case lists:member("hometree", Plugins) of - true -> - create_node(Host, ServerHost, string_to_node("/home"), service_jid(Host), "hometree"), - create_node(Host, ServerHost, string_to_node("/home/" ++ ServerHost), service_jid(Host), "hometree"); - false -> - ok + true -> + create_node(Host, ServerHost, string_to_node("/home"), service_jid(Host), "hometree"), + create_node(Host, ServerHost, string_to_node("/home/" ++ ServerHost), service_jid(Host), "hometree"); + false -> + ok end. + +-spec(update_node_database/2 :: + ( + Host :: string(), + ServerHost :: string()) + -> {'aborted',_} | {'atomic',_} + ). + update_node_database(Host, ServerHost) -> mnesia:del_table_index(pubsub_node, type), mnesia:del_table_index(pubsub_node, parentid), @@ -294,50 +370,50 @@ update_node_database(Host, ServerHost) -> ?INFO_MSG("upgrade node pubsub tables",[]), F = fun() -> {Result, LastIdx} = lists:foldl( - fun({pubsub_node, NodeId, ParentId, {nodeinfo, Items, Options, Entities}}, {RecList, Nidx}) -> - ItemsList = - lists:foldl( - fun({item, ItemName, Publisher, Payload}, Acc) -> - C = {unknown, Publisher}, - M = {now(), Publisher}, - mnesia:write( - #pubsub_item{id = {ItemName, Nidx}, - creation = C, - modification = M, - payload = Payload}), - [{Publisher, ItemName} | Acc] - end, [], Items), - Owners = - dict:fold( - fun(JID, {entity, Aff, Sub}, Acc) -> - UsrItems = - lists:foldl( - fun({P, I}, IAcc) -> - case P of - JID -> [I | IAcc]; - _ -> IAcc - end - end, [], ItemsList), - mnesia:write({pubsub_state, - {JID, Nidx}, - UsrItems, - Aff, - Sub}), - case Aff of - owner -> [JID | Acc]; - _ -> Acc - end - end, [], Entities), - mnesia:delete({pubsub_node, NodeId}), - {[#pubsub_node{id = NodeId, - idx = Nidx, - parents = [element(2, ParentId)], - owners = Owners, - options = Options} | - RecList], Nidx + 1} - end, {[], 1}, - mnesia:match_object - ({pubsub_node, {Host, '_'}, '_', '_'})), + fun({pubsub_node, NodeId, ParentId, {nodeinfo, Items, Options, Entities}}, {RecList, Nidx}) -> + ItemsList = + lists:foldl( + fun({item, ItemName, Publisher, Payload}, Acc) -> + C = {unknown, Publisher}, + M = {now(), Publisher}, + mnesia:write( + #pubsub_item{id = {ItemName, Nidx}, + creation = C, + modification = M, + payload = Payload}), + [{Publisher, ItemName} | Acc] + end, [], Items), + Owners = + dict:fold( + fun(JID, {entity, Aff, Sub}, Acc) -> + UsrItems = + lists:foldl( + fun({P, I}, IAcc) -> + case P of + JID -> [I | IAcc]; + _ -> IAcc + end + end, [], ItemsList), + mnesia:write({pubsub_state, + {JID, Nidx}, + UsrItems, + Aff, + Sub}), + case Aff of + owner -> [JID | Acc]; + _ -> Acc + end + end, [], Entities), + mnesia:delete({pubsub_node, NodeId}), + {[#pubsub_node{id = NodeId, + idx = Nidx, + parents = [element(2, ParentId)], + owners = Owners, + options = Options} | + RecList], Nidx + 1} + end, {[], 1}, + mnesia:match_object + ({pubsub_node, {Host, '_'}, '_', '_'})), mnesia:write(#pubsub_index{index = node, last = LastIdx, free = []}), Result end, @@ -358,40 +434,40 @@ update_node_database(Host, ServerHost) -> end; [nodeid, parentid, type, owners, options] -> F = fun({pubsub_node, NodeId, {_, Parent}, Type, Owners, Options}) -> - #pubsub_node{ - id = NodeId, - idx = 0, - parents = [Parent], - type = Type, - owners = Owners, - options = Options} + #pubsub_node{ + id = NodeId, + idx = 0, + parents = [Parent], + type = Type, + owners = Owners, + options = Options} end, - %% TODO : to change nodeid/id and id/idx or not to change ? + %% TODO : to change nodeid/id and id/idx or not to change ? mnesia:transform_table(pubsub_node, F, [nodeid, id, parents, type, owners, options]), FNew = fun() -> - LastIdx = lists:foldl(fun(#pubsub_node{id = NodeId} = PubsubNode, Nidx) -> - mnesia:write(PubsubNode#pubsub_node{idx = Nidx}), - lists:foreach(fun(#pubsub_state{id = StateId} = State) -> - {JID, _} = StateId, - mnesia:delete({pubsub_state, StateId}), - mnesia:write(State#pubsub_state{id = {JID, Nidx}}) - end, mnesia:match_object(#pubsub_state{id = {'_', NodeId}, _ = '_'})), - lists:foreach(fun(#pubsub_item{id = ItemId} = Item) -> - {ItemName, _} = ItemId, - {M1, M2} = Item#pubsub_item.modification, - {C1, C2} = Item#pubsub_item.creation, - mnesia:delete({pubsub_item, ItemId}), - mnesia:write(Item#pubsub_item{id = {ItemName, Nidx}, - modification = {M2, M1}, - creation = {C2, C1}}) - end, mnesia:match_object(#pubsub_item{id = {'_', NodeId}, _ = '_'})), - Nidx + 1 - end, 1, mnesia:match_object - ({pubsub_node, {Host, '_'}, '_', '_', '_', '_', '_'}) - ++ mnesia:match_object - ({pubsub_node, {{'_', ServerHost, '_'}, '_'}, '_', '_', '_', '_', '_'})), - mnesia:write(#pubsub_index{index = node, last = LastIdx, free = []}) - end, + LastIdx = lists:foldl(fun(#pubsub_node{id = NodeId} = PubsubNode, Nidx) -> + mnesia:write(PubsubNode#pubsub_node{idx = Nidx}), + lists:foreach(fun(#pubsub_state{id = StateId} = State) -> + {JID, _} = StateId, + mnesia:delete({pubsub_state, StateId}), + mnesia:write(State#pubsub_state{id = {JID, Nidx}}) + end, mnesia:match_object(#pubsub_state{id = {'_', NodeId}, _ = '_'})), + lists:foreach(fun(#pubsub_item{id = ItemId} = Item) -> + {ItemName, _} = ItemId, + {M1, M2} = Item#pubsub_item.modification, + {C1, C2} = Item#pubsub_item.creation, + mnesia:delete({pubsub_item, ItemId}), + mnesia:write(Item#pubsub_item{id = {ItemName, Nidx}, + modification = {M2, M1}, + creation = {C2, C1}}) + end, mnesia:match_object(#pubsub_item{id = {'_', NodeId}, _ = '_'})), + Nidx + 1 + end, 1, mnesia:match_object + ({pubsub_node, {Host, '_'}, '_', '_', '_', '_', '_'}) + ++ mnesia:match_object + ({pubsub_node, {{'_', ServerHost, '_'}, '_'}, '_', '_', '_', '_', '_'})), + mnesia:write(#pubsub_index{index = node, last = LastIdx, free = []}) + end, case mnesia:transaction(FNew) of {atomic, Result} -> rename_default_nodeplugin(), @@ -401,46 +477,57 @@ update_node_database(Host, ServerHost) -> end; [nodeid, id, parent, type, owners, options] -> F = fun({pubsub_node, NodeId, Id, Parent, Type, Owners, Options}) -> - #pubsub_node{ - id = NodeId, - idx = Id, - parents = [Parent], - type = Type, - owners = Owners, - options = Options} + #pubsub_node{ + id = NodeId, + idx = Id, + parents = [Parent], + type = Type, + owners = Owners, + options = Options} end, - %% TODO : to change nodeid/id and id/idx or not to change ? + %% TODO : to change nodeid/id and id/idx or not to change ? mnesia:transform_table(pubsub_node, F, [nodeid, id, parents, type, owners, options]), rename_default_nodeplugin(); _ -> ok end, mnesia:transaction(fun() -> - case catch mnesia:first(pubsub_node) of - {_, L} when is_list(L) -> - lists:foreach( - fun({H, N}) when is_list(N) -> - [Node] = mnesia:read({pubsub_node, {H, N}}), - Type = Node#pubsub_node.type, - BN = element(2, node_call(Type, path_to_node, [N])), - BP = case [element(2, node_call(Type, path_to_node, [P])) || P <- Node#pubsub_node.parents] of - [<<>>] -> []; - Parents -> Parents - end, - mnesia:write(Node#pubsub_node{id={H, BN}, parents=BP}), - mnesia:delete({pubsub_node, {H, N}}); - (_) -> - ok - end, mnesia:all_keys(pubsub_node)); - _ -> - ok - end - end). + case catch mnesia:first(pubsub_node) of + {_, L} when is_list(L) -> + lists:foreach( + fun({H, N}) when is_list(N) -> + [Node] = mnesia:read({pubsub_node, {H, N}}), + Type = Node#pubsub_node.type, + BN = element(2, node_call(Type, path_to_node, [N])), + BP = case [element(2, node_call(Type, path_to_node, [P])) || P <- Node#pubsub_node.parents] of + [<<>>] -> []; + Parents -> Parents + end, + mnesia:write(Node#pubsub_node{id={H, BN}, parents=BP}), + mnesia:delete({pubsub_node, {H, N}}); + (_) -> + ok + end, mnesia:all_keys(pubsub_node)); + _ -> + ok + end + end). + + +-spec(rename_default_nodeplugin/0 :: () -> 'ok'). rename_default_nodeplugin() -> lists:foreach(fun(Node) -> - mnesia:dirty_write(Node#pubsub_node{type = "hometree"}) - end, mnesia:dirty_match_object(#pubsub_node{type = "default", _ = '_'})). + mnesia:dirty_write(Node#pubsub_node{type = "hometree"}) + end, mnesia:dirty_match_object(#pubsub_node{type = "default", _ = '_'})). + + +-spec(update_state_database/2 :: + ( + Host :: string(), + ServerHost :: string()) + -> 'ok' + ). update_state_database(_Host, _ServerHost) -> case catch mnesia:table_info(pubsub_state, attributes) of @@ -481,236 +568,340 @@ update_state_database(_Host, _ServerHost) -> ok end. + +-spec(send_loop/1 :: + ( + State::#state{}) + -> 'ok' + ). + send_loop(State) -> receive - {presence, JID, Pid} -> - Host = State#state.host, - ServerHost = State#state.server_host, - LJID = jlib:short_prepd_jid(JID), - BJID = jlib:short_prepd_bare_jid(JID), - %% for each node From is subscribed to - %% and if the node is so configured, send the last published item to From - lists:foreach(fun(PType) -> - {result, Subscriptions} = node_action(Host, PType, get_entity_subscriptions, [Host, JID]), - lists:foreach( - fun({Node, subscribed, _, SubJID}) -> - if (SubJID == LJID) or (SubJID == BJID) -> - #pubsub_node{id = {H, N}, type = Type, idx = Nidx, options = Options} = Node, - case get_option(Options, send_last_published_item) of - on_sub_and_presence -> - send_items(H, N, Nidx, Type, LJID, last); - _ -> - ok - end; - true -> - % resource not concerned about that subscription - ok - end; - (_) -> - ok - end, Subscriptions) - end, State#state.plugins), - %% and force send the last PEP events published by its offline and local contacts - %% only if pubsub is explicitely configured for that. - %% this is a hack in a sense that PEP should only be based on presence - %% and is not able to "store" events of remote users (via s2s) - %% this makes that hack only work for local domain by now - if not State#state.ignore_pep_from_offline -> - {User, Server, Resource} = LJID, - case catch ejabberd_c2s:get_subscribed(Pid) of - Contacts when is_list(Contacts) -> - lists:foreach( - fun({U, S, R}) -> - case S of - ServerHost -> %% local contacts - case user_resources(U, S) of - [] -> %% offline - PeerJID = exmpp_jid:make(U, S, R), - self() ! {presence, User, Server, [Resource], PeerJID}; - _ -> %% online - % this is already handled by presence probe - ok - end; - _ -> %% remote contacts - % we can not do anything in any cases - ok - end - end, Contacts); - _ -> - ok - end; - true -> - ok - end, - send_loop(State); - {presence, User, Server, Resources, JID} -> - %% get resources caps and check if processing is needed - spawn(fun() -> - Host = State#state.host, - Owner = jlib:short_prepd_bare_jid(JID), - lists:foreach(fun(#pubsub_node{id = {_, Node}, type = Type, idx = Nidx, options = Options}) -> - case get_option(Options, send_last_published_item) of - on_sub_and_presence -> - lists:foreach(fun(Resource) -> - LJID = {User, Server, Resource}, - Subscribed = case get_option(Options, access_model) of - open -> true; - presence -> true; - whitelist -> false; % subscribers are added manually - authorize -> false; % likewise - roster -> - Grps = get_option(Options, roster_groups_allowed, []), - {OU, OS, _} = Owner, - element(2, get_roster_info(OU, OS, LJID, Grps)) - end, - if Subscribed -> send_items(Owner, Node, Nidx, Type, LJID, last); - true -> ok - end - end, Resources); + {'presence', #jid{node = User, domain = Server, resource = Resource} = JID, Pid} -> + Host = State#state.host, + ServerHost = State#state.server_host, + LJID = {User,Server,Resource}, + BJID = {User,Server,undefined}, + %% for each node From is subscribed to + %% and if the node is so configured, send the last published item to From + lists:foreach(fun(PType) -> + {result, Subscriptions} = node_action(Host, PType, get_entity_subscriptions, [Host, JID]), + lists:foreach( + fun({Node, subscribed, _, SubJID}) -> + if (SubJID == LJID) or (SubJID == BJID) -> + #pubsub_node{id = {H, NodeId}, type = Type, idx = NodeIdx, options = Options} = Node, + case get_option(Options, 'send_last_published_item') of + 'on_sub_and_presence' -> + send_items(H, NodeId, NodeIdx, Type, LJID, 'last'); + _ -> + ok + end; + true -> + % resource not concerned about that subscription + ok + end; + (_) -> + ok + end, Subscriptions) + end, State#state.plugins), + %% and force send the last PEP events published by its offline and local contacts + %% only if pubsub is explicitely configured for that. + %% this is a hack in a sense that PEP should only be based on presence + %% and is not able to "store" events of remote users (via s2s) + %% this makes that hack only work for local domain by now + if not State#state.ignore_pep_from_offline -> + case catch ejabberd_c2s:get_subscribed(Pid) of + Contacts when is_list(Contacts) -> + lists:foreach( + fun({U, S, R}) -> + case S of + ServerHost -> %% local contacts + case user_resources(U, S) of + [] -> %% offline + PeerJID = exmpp_jid:make(U, S, R), + self() ! {'presence', User, Server, [Resource], PeerJID}; + _ -> %% online + % this is already handled by presence probe + ok + end; + _ -> %% remote contacts + % we can not do anything in any cases + ok + end + end, Contacts); _ -> ok - end - end, tree_action(Host, get_nodes, [Owner, JID])) - end), - send_loop(State); - stop -> - ok + end; + true -> + ok + end, + send_loop(State); + {'presence', User, Server, Resources, #jid{node = U, domain = S} = JID} -> + %% get resources caps and check if processing is needed + spawn(fun() -> + Host = State#state.host, + Owner = {U,S,undefined}, + lists:foreach(fun(#pubsub_node{id = {_, NodeId}, type = Type, idx = NodeIdx, options = Options}) -> + case get_option(Options, 'send_last_published_item') of + 'on_sub_and_presence' -> + lists:foreach(fun(Resource) -> + LJID = {User, Server, Resource}, + Subscribed = case get_option(Options, 'access_model') of + 'open' -> true; + 'presence' -> true; + 'whitelist' -> false; % subscribers are added manually + 'authorize' -> false; % likewise + 'roster' -> + RosterGroups = get_option(Options, 'roster_groups_allowed', []), + element(2, get_roster_info(U, S, LJID, RosterGroups)) + end, + if Subscribed -> send_items(Owner, NodeId, NodeIdx, Type, LJID, 'last'); + true -> ok + end + end, Resources); + _ -> + ok + end + end, tree_action(Host, get_nodes, [Owner, JID])) + end), + send_loop(State); + stop -> + ok end. %% ------- %% disco hooks handling functions %% +-spec(disco_local_identity/5 :: + ( + Acc :: [] | [Identity::#xmlel{name::'identity',ns::?NS_DISCO_INFO}], + From :: jidEntity(), + To :: jidComponent(), + NodeId :: nodeId(), + Lang :: binary()) + -> Identities :: [] | [Identity::#xmlel{name::'identity',ns::?NS_DISCO_INFO}] + ). -disco_local_identity(Acc, _From, To, <<>>, _Lang) -> - case lists:member(?PEPNODE, plugins(exmpp_jid:prep_domain_as_list(To))) of +disco_local_identity(Acc, _From, #jid{domain = Host} = _To, <<>> = _NodeId, _Lang) -> + case lists:member(?PEPNODE, plugins(Host)) of true -> [#xmlel{name = 'identity', ns = ?NS_DISCO_INFO, attrs = [?XMLATTR('category', <<"pubsub">>), ?XMLATTR('type', <<"pep">>)]} - | Acc]; + | Acc]; false -> Acc end; -disco_local_identity(Acc, _From, _To, _Node, _Lang) -> +disco_local_identity(Acc, _From, _To, _NodeId, _Lang) -> Acc. -disco_local_features(Acc, _From, To, <<>>, _Lang) -> - Host = exmpp_jid:prep_domain_as_list(To), - Feats = case Acc of - {result, I} -> I; - _ -> [] - end, - {result, Feats ++ lists:map(fun(Feature) -> - ?NS_PUBSUB_s++"#"++Feature - end, features(Host, <<>>))}; -disco_local_features(Acc, _From, _To, _Node, _Lang) -> + +-spec(disco_local_features/5 :: + ( + Acc :: 'empty' | {'result', Features :: [] | [Feature :: atom() | string() | binary()]}, + From :: jidEntity(), + To :: jidComponent(), + NodeId :: nodeId(), + Lang :: binary()) + -> {'result', Features :: [] | [Feature :: atom() | string() | binary()]} + ). + +disco_local_features(Acc, _From, #jid{domain = Host} = _To, <<>> = _NodeId, _Lang) -> + OtherFeatures = case Acc of + {result, Features} -> Features; + _ -> [] + end, + {result, OtherFeatures ++ + [?NS_PUBSUB_s++"#"++Feature || Feature <- features(Host, <<>>)]}; +disco_local_features(Acc, _From, _To, _NodeId, _Lang) -> Acc. + +-spec(disco_local_items/5 :: + ( + Acc :: {'result', Items :: [] | [Item::#xmlel{name::'item',ns::?NS_DISCO_INFO}]}, + From :: jidEntity(), + To :: jidComponent(), + NodeId :: nodeId(), + Lang :: binary()) + -> {'result', Items :: [] | [Item::#xmlel{name::'item',ns::?NS_DISCO_INFO}]} + | {'error', _} %% TODO + ). + disco_local_items(Acc, _From, _To, <<>>, _Lang) -> Acc; disco_local_items(Acc, _From, _To, _Node, _Lang) -> Acc. -disco_sm_identity(Acc, From, To, Node, _Lang) -> - disco_identity(To, Node, From) ++ Acc. -disco_identity(_Host, <<>>, _From) -> +-spec(disco_sm_identity/5 :: + ( + Acc :: [] | [Identity::#xmlel{name::'identity',ns::?NS_DISCO_INFO}], + From :: jidEntity(), + To :: jidContact(), + NodeId :: nodeId(), + Lang :: binary()) + -> Identities :: [] | [Identity::#xmlel{name::'identity',ns::?NS_DISCO_INFO}] + ). + +disco_sm_identity(Acc, From, To, NodeId, _Lang) -> + disco_identity(To, NodeId, From) ++ Acc. + + +-spec(disco_identity/3 :: + ( + Host :: jidContact(), + NodeId :: nodeId(), + From :: jidEntity()) + -> Identities :: [] | [Identity::#xmlel{name::'identity',ns::?NS_DISCO_INFO}] + ). + +disco_identity(_Host, <<>> = _NodeId, _From) -> [#xmlel{name = 'identity', ns = ?NS_DISCO_INFO, - attrs = [?XMLATTR('category', <<"pubsub">>), ?XMLATTR('type', <<"pep">>)]}]; -disco_identity(Host, Node, From) -> - Action = fun(#pubsub_node{idx = Nidx, type = Type, options = Options, owners = Owners}) -> - case get_allowed_items_call(Host, Nidx, From, Type, Options, Owners) of - {result, _} -> - {result, - [#xmlel{name = 'identity', ns = ?NS_DISCO_INFO, - attrs = [?XMLATTR('category', <<"pubsub">>), ?XMLATTR('type', <<"pep">>)]}, - #xmlel{name = 'identity', ns = ?NS_DISCO_INFO, - attrs = [?XMLATTR('category', <<"pubsub">>), ?XMLATTR('type', <<"leaf">>) - | case get_option(Options, title) of - false -> []; - Title -> [?XMLATTR('name', Title)] - end - ]}]}; - {error, _} -> {result, []} - end - end, - case transaction(exmpp_jid:to_lower(Host), Node, Action, sync_dirty) of + attrs = [?XMLATTR('category', <<"pubsub">>), ?XMLATTR('type', <<"pep">>)]}]; +disco_identity(#jid{node = U, domain = S, resource = R} = Host, NodeId, From) -> + Action = fun(#pubsub_node{idx = NodeIdx, type = Type, options = Options, owners = Owners}) -> + case get_allowed_items_call(Host, NodeIdx, From, Type, Options, Owners) of + {result, _} -> + {result, + [#xmlel{name = 'identity', ns = ?NS_DISCO_INFO, + attrs = [?XMLATTR('category', <<"pubsub">>), ?XMLATTR('type', <<"pep">>)]}, + #xmlel{name = 'identity', ns = ?NS_DISCO_INFO, + attrs = [?XMLATTR('category', <<"pubsub">>), ?XMLATTR('type', <<"leaf">>) + | case get_option(Options, 'title') of + false -> []; + Title -> [?XMLATTR('name', Title)] + end + ]}]}; + {error, _} -> {result, []} + end + end, + case transaction({U,S,R}, NodeId, Action, sync_dirty) of + {result, {_, Identities}} -> Identities; + _ -> _Identities = [] + end. + + +-spec(disco_sm_features/5 :: + ( + Acc :: 'empty' | {'result', Features :: [] | [Feature :: atom() | string() | binary()]}, + From :: jidEntity(), + To :: jidContact(), + NodeId :: nodeId(), + Lang :: binary()) + -> {'result', Features :: [] | [Feature :: atom() | string() | binary()]} + ). + +disco_sm_features('empty' = _Acc, From, To, NodeId, Lang) -> + disco_sm_features({result, []}, From, To, NodeId, Lang); +disco_sm_features({result, OtherFeatures} = _Acc, From, To, NodeId, _Lang) -> + {result, disco_features(To, NodeId, From) ++ OtherFeatures}. + + +-spec(disco_features/3 :: + ( + Host :: jidContact(), + NodeId :: nodeId(), + From :: jidEntity()) + -> Features :: [] | [Feature :: atom() | string() | binary()] + ). + +disco_features(_Host, <<>> = _NodeId, _From) -> + [?NS_PUBSUB_s + | [?NS_PUBSUB_s++"#"++Feature || Feature <- features("pep")]]; +disco_features(#jid{node = U, domain = S, resource = R} = Host, NodeId, From) -> + Action = fun(#pubsub_node{idx = NodeIdx, type = Type, options = Options, owners = Owners}) -> + case get_allowed_items_call(Host, NodeIdx, From, Type, Options, Owners) of + {result, _} -> + {result, [?NS_PUBSUB_s + | [?NS_PUBSUB_s ++ "#" ++ Feature || Feature <- features("pep")]]}; + _ -> {result, []} + end + end, + case transaction({U,S,R}, NodeId, Action, sync_dirty) of + {result, {_, Features}} -> Features; + _ -> _Features = [] + end. + + +-spec(disco_sm_items/5 :: + ( + Acc :: 'empty' + | {'result', Items :: [] | [Item::#xmlel{name::'item',ns::?NS_DISCO_INFO}]}, + From :: jidEntity(), + To :: jidContact(), + NodeId :: nodeId(), + Lang :: binary()) + -> {'result', Items :: [] | [Item::#xmlel{name::'item',ns::?NS_DISCO_INFO}]} + ). + +disco_sm_items('empty' = _Acc, From, To, NodeId, Lang) -> + disco_sm_items({result, []}, From, To, NodeId, Lang); +disco_sm_items({result, OtherItems} = _Acc, From, To, NodeId, _Lang) -> + {result, disco_items(To, NodeId, From) ++ OtherItems}. + + +-spec(disco_items/3 :: + ( + Host :: jidContact(), + NodeId :: nodeId(), + From :: jidEntity()) + -> Items :: [] | [Item::#xmlel{name::'item',ns::?NS_DISCO_INFO}] + ). + +disco_items(#jid{raw = JID, node = U, domain = S, resource = R} = Host, <<>>, From) -> + Action = fun(#pubsub_node{id ={_, NodeId}, options = Options, type = Type, idx = NodeIdx, owners = Owners}, Acc) -> + case get_allowed_items_call(Host, NodeIdx, From, Type, Options, Owners) of + {result, _} -> + [#xmlel{name = 'item', ns = ?NS_DISCO_INFO, + attrs = [?XMLATTR('jid', JID), + ?XMLATTR('node', NodeId) | + case get_option(Options, 'title') of + false -> []; + [Title] -> [?XMLATTR('title', Title)] + end]} + | Acc]; + _ -> Acc + end + end, + case transaction({U,S,R}, Action, sync_dirty) of + {result, Items} -> Items + %_ -> _Items = [] + end; + +disco_items(#jid{raw = JID, node = U, domain = S, resource = R} = Host, NodeId, From) -> + Action = fun(#pubsub_node{idx = NodeIdx, type = Type, options = Options, owners = Owners}) -> + case get_allowed_items_call(Host, NodeIdx, From, Type, Options, Owners) of + {result, Items} -> + {result, + [#xmlel{name = 'item', ns = ?NS_DISCO_INFO, + attrs = [?XMLATTR('jid', JID), + ?XMLATTR('name', ItemId)]} + || #pubsub_item{id = {ItemId,_}} <- Items]}; + _ -> {result, []} + end + end, + case transaction({U,S,R}, NodeId, Action, sync_dirty) of {result, {_, Result}} -> Result; _ -> [] end. - -disco_sm_features(empty, From, To, Node, Lang) -> - disco_sm_features({result, []}, From, To, Node, Lang); -disco_sm_features({result, OtherFeatures}, From, To, Node, _Lang) -> - {result, disco_features(To, Node, From) ++ OtherFeatures}. - -disco_features(_Host, <<>>, _From) -> - [?NS_PUBSUB_s - | [?NS_PUBSUB_s++"#"++Feature || Feature <- features("pep")]]; -disco_features(Host, Node, From) -> - Action = fun(#pubsub_node{idx = Nidx, type = Type, options = Options, owners = Owners}) -> - case get_allowed_items_call(Host, Nidx, From, Type, Options, Owners) of - {result, _} -> - {result, [?NS_PUBSUB_s - | [?NS_PUBSUB_s ++ "#" ++ Feature || Feature <- features("pep")]]}; - _ -> {result, []} - end - end, - case transaction(exmpp_jid:to_lower(Host), Node, Action, sync_dirty) of - {result, {_, Result}} -> Result; - _ -> [] - end. - -disco_sm_items(empty, From, To, Node, Lang) -> - disco_sm_items({result, []}, From, To, Node, Lang); -disco_sm_items({result, OtherItems}, From, To, Node, _Lang) -> - {result, disco_items(To, Node, From) ++ OtherItems}. - -disco_items(Host, <<>>, From) -> - Action = fun(#pubsub_node{id ={_, NodeId}, options = Options, type = Type, idx = Nidx, owners = Owners}, Acc) -> - case get_allowed_items_call(Host, Nidx, From, Type, Options, Owners) of - {result, _} -> - [#xmlel{name = 'item', ns = ?NS_DISCO_INFO, - attrs = [?XMLATTR('jid', exmpp_jid:to_binary(Host)), - ?XMLATTR('node', NodeId) | - case get_option(Options, title) of - false -> []; - [Title] -> [?XMLATTR('title', Title)] - end]} - | Acc]; - _ -> Acc - end - end, - case transaction(exmpp_jid:to_lower(Host), Action, sync_dirty) of - {result, Result} -> Result; - _ -> [] - end; - -disco_items(Host, Node, From) -> - Action = fun(#pubsub_node{idx = Nidx, type = Type, options = Options, owners = Owners}) -> - case get_allowed_items_call(Host, Nidx, From, Type, Options, Owners) of - {result, Items} -> - {result, - [#xmlel{name = 'item', ns = ?NS_DISCO_INFO, - attrs = [?XMLATTR('jid', exmpp_jid:to_binary(Host)), - ?XMLATTR('name', ItemId)]} - || #pubsub_item{id = {ItemId,_}} <- Items]}; - _ -> {result, []} - end - end, - case transaction(exmpp_jid:to_lower(Host), Node, Action, sync_dirty) of - {result, {_, Result}} -> Result; - _ -> [] - end. - %% ------- %% presence hooks handling functions %% -presence_probe(Peer, JID, Pid) -> +-spec(presence_probe/3 :: + ( + Peer :: jidEntity(), + JID :: jidEntity(), + Pid :: pid()) + -> 'ok' + | {'presence', JID::jidEntity(), Pid::pid()} + | {'presence', User::binary(), Server::binary(), [Resource::binary()], JID::jidEntity()} + ). + +presence_probe(#jid{node = User, domain = Server, resource = Resource} = Peer, #jid{domain = Host} = JID, Pid) -> case exmpp_jid:full_compare(Peer, JID) of true -> %% JID are equals - {User, Server, Resource} = jlib:short_prepd_jid(Peer), - presence(Server, {presence, JID, Pid}), - presence(Server, {presence, User, Server, [Resource], JID}); + presence(Server, {'presence', JID, Pid}), + presence(Server, {'presence', User, Server, [Resource], JID}); false -> case exmpp_jid:bare_compare(Peer, JID) of true -> @@ -718,32 +909,40 @@ presence_probe(Peer, JID, Pid) -> %% this way, we do not send duplicated last items if user already connected with other clients ok; false -> - {User, Server, Resource} = jlib:short_prepd_jid(Peer), - Host = exmpp_jid:prep_domain_as_list(JID), - presence(Host, {presence, User, Server, [Resource], JID}) + presence(Host, {'presence', User, Server, [Resource], JID}) end end. + +-spec(presence/2 :: + ( + ServerHost :: string() | binary(), + Presence :: {'presence', JID::jidEntity(), Pid::pid()} + | {'presence', User::binary(), Server::binary(), [Resource::binary()], JID::jidEntity()}) + -> {'presence', JID::jidEntity(), Pid::pid()} + | {'presence', User::binary(), Server::binary(), [Resource::binary()], JID::jidEntity()} + ). + presence(ServerHost, Presence) when is_binary(ServerHost) -> presence(binary_to_list(ServerHost), Presence); presence(ServerHost, Presence) -> SendLoop = case whereis(gen_mod:get_module_proc(ServerHost, ?LOOPNAME)) of - undefined -> - % in case send_loop process died, we rebuild a minimal State record and respawn it - Host = host(ServerHost), - Plugins = plugins(Host), - PepOffline = case catch ets:lookup(gen_mod:get_module_proc(ServerHost, config), ignore_pep_from_offline) of - [{ignore_pep_from_offline, PO}] -> PO; - _ -> true - end, - State = #state{host = Host, - server_host = ServerHost, - ignore_pep_from_offline = PepOffline, - plugins = Plugins}, - init_send_loop(ServerHost, State); - Pid -> - Pid - end, + undefined -> + % in case send_loop process died, we rebuild a minimal State record and respawn it + Host = host(ServerHost), + Plugins = plugins(Host), + PepOffline = case catch ets:lookup(gen_mod:get_module_proc(ServerHost, 'config'), 'ignore_pep_from_offline') of + [{'ignore_pep_from_offline', PO}] -> PO; + _ -> true + end, + State = #state{host = Host, + server_host = ServerHost, + ignore_pep_from_offline = PepOffline, + plugins = Plugins}, + init_send_loop(ServerHost, State); + Pid -> + Pid + end, SendLoop ! Presence. %% ------- @@ -754,9 +953,9 @@ out_subscription(User, Server, JID, subscribed) -> Owner = exmpp_jid:make(User, Server, ""), {U, S, R} = jlib:short_prepd_jid(JID), Rs = case R of - undefined -> user_resources(U, S); - _ -> [R] - end, + undefined -> user_resources(U, S); + _ -> [R] + end, presence(Server, {presence, U, S, Rs, Owner}), true; out_subscription(_, _, _, _) -> @@ -771,26 +970,26 @@ unsubscribe_user(Entity, Owner) -> BJID = jlib:short_prepd_bare_jid(Owner), Host = host(element(2, BJID)), spawn(fun() -> - lists:foreach(fun(PType) -> - {result, Subscriptions} = node_action(Host, PType, get_entity_subscriptions, [Host, Entity]), - lists:foreach(fun - ({#pubsub_node{options = Options, owners = Owners, idx = Nidx}, subscribed, _, JID}) -> - case get_option(Options, access_model) of - presence -> - case lists:member(BJID, Owners) of - true -> - node_action(Host, PType, unsubscribe_node, [Nidx, Entity, JID, all]); - false -> - {result, ok} - end; - _ -> - {result, ok} - end; - (_) -> - ok - end, Subscriptions) - end, plugins(Host)) - end). + lists:foreach(fun(PType) -> + {result, Subscriptions} = node_action(Host, PType, get_entity_subscriptions, [Host, Entity]), + lists:foreach(fun + ({#pubsub_node{options = Options, owners = Owners, idx = Nidx}, subscribed, _, JID}) -> + case get_option(Options, access_model) of + presence -> + case lists:member(BJID, Owners) of + true -> + node_action(Host, PType, unsubscribe_node, [Nidx, Entity, JID, all]); + false -> + {result, ok} + end; + _ -> + {result, ok} + end; + (_) -> + ok + end, Subscriptions) + end, plugins(Host)) + end). %% ------- %% user remove hook handling function @@ -806,21 +1005,21 @@ remove_user(UserB, ServerB) -> Host = host(LServer), HomeTreeBase = string_to_node("/home/"++LServer++"/"++LUser), spawn(fun() -> - %% remove user's subscriptions - lists:foreach(fun(PType) -> - {result, Subscriptions} = node_action(Host, PType, get_entity_subscriptions, [Host, Entity]), - lists:foreach(fun - ({#pubsub_node{idx = Nidx}, _, _, JID}) -> node_action(Host, PType, unsubscribe_node, [Nidx, Entity, JID, all]) - end, Subscriptions), - {result, Affiliations} = node_action(Host, PType, get_entity_affiliations, [Host, Entity]), - lists:foreach(fun - ({#pubsub_node{id = {H, N}, parents = []}, owner}) -> delete_node(H, N, Entity); - ({#pubsub_node{id = {H, N}, type = "hometree"}, owner}) when N == HomeTreeBase -> delete_node(H, N, Entity); - ({#pubsub_node{idx = Nidx}, publisher}) -> node_action(Host, PType, set_affiliation, [Nidx, Entity, none]); - (_) -> ok - end, Affiliations) - end, plugins(Host)) - end). + %% remove user's subscriptions + lists:foreach(fun(PType) -> + {result, Subscriptions} = node_action(Host, PType, get_entity_subscriptions, [Host, Entity]), + lists:foreach(fun + ({#pubsub_node{idx = Nidx}, _, _, JID}) -> node_action(Host, PType, unsubscribe_node, [Nidx, Entity, JID, all]) + end, Subscriptions), + {result, Affiliations} = node_action(Host, PType, get_entity_affiliations, [Host, Entity]), + lists:foreach(fun + ({#pubsub_node{id = {H, N}, parents = []}, owner}) -> delete_node(H, N, Entity); + ({#pubsub_node{id = {H, N}, type = "hometree"}, owner}) when N == HomeTreeBase -> delete_node(H, N, Entity); + ({#pubsub_node{idx = Nidx}, publisher}) -> node_action(Host, PType, set_affiliation, [Nidx, Entity, none]); + (_) -> ok + end, Affiliations) + end, plugins(Host)) + end). %%-------------------------------------------------------------------- %% Function: @@ -861,17 +1060,28 @@ handle_cast(_Msg, State) -> %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- %% @private -handle_info({route, From, To, Packet}, +-spec(handle_info/2 :: + ( + Info :: {'route', + From :: jidEntity(), + To :: jidComponent(), + Packet :: #xmlel{name :: 'iq' | 'message' | 'presence'}}, + State :: #state{}) + -> {'noreply', State::#state{}} + ). +%% TODO : what to do when JID recipient contains a resource ? +handle_info({route, From, + #jid{node = undefined, domain = Host, resource = undefined} = To, Packet}, #state{server_host = ServerHost, access = Access, plugins = Plugins} = State) -> - case catch do_route(ServerHost, Access, Plugins, exmpp_jid:prep_domain_as_list(To), From, To, Packet) of + case catch do_route(list_to_binary(ServerHost), Access, Plugins, Host, From, To, Packet) of {'EXIT', Reason} -> ?ERROR_MSG("~p", [Reason]); _ -> ok end, - {noreply, State}; + {'noreply', State}; handle_info(_Info, State) -> - {noreply, State}. + {'noreply', State}. %% TODO : handle other case with recipient full JID %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() @@ -881,6 +1091,13 @@ handle_info(_Info, State) -> %% The return value is ignored. %%-------------------------------------------------------------------- %% @private +-spec(terminate/2 :: + ( + Reason :: _, + State :: #state{}) + -> 'ok' + ). + terminate(_Reason, #state{host = Host, server_host = ServerHost, nodetree = TreePlugin, @@ -888,15 +1105,15 @@ terminate(_Reason, #state{host = Host, ejabberd_router:unregister_route(Host), ServerHostB = list_to_binary(ServerHost), case lists:member(?PEPNODE, Plugins) of - true -> - ejabberd_hooks:delete(feature_check_packet, ServerHostB, ?MODULE, feature_check_packet, 75), - ejabberd_hooks:delete(disco_sm_identity, ServerHostB, ?MODULE, disco_sm_identity, 75), - ejabberd_hooks:delete(disco_sm_features, ServerHostB, ?MODULE, disco_sm_features, 75), - ejabberd_hooks:delete(disco_sm_items, ServerHostB, ?MODULE, disco_sm_items, 75), - gen_iq_handler:remove_iq_handler(ejabberd_sm, ServerHostB, ?NS_PUBSUB), - gen_iq_handler:remove_iq_handler(ejabberd_sm, ServerHostB, ?NS_PUBSUB_OWNER); - false -> - ok + true -> + ejabberd_hooks:delete(feature_check_packet, ServerHostB, ?MODULE, feature_check_packet, 75), + ejabberd_hooks:delete(disco_sm_identity, ServerHostB, ?MODULE, disco_sm_identity, 75), + ejabberd_hooks:delete(disco_sm_features, ServerHostB, ?MODULE, disco_sm_features, 75), + ejabberd_hooks:delete(disco_sm_items, ServerHostB, ?MODULE, disco_sm_items, 75), + gen_iq_handler:remove_iq_handler(ejabberd_sm, ServerHostB, ?NS_PUBSUB), + gen_iq_handler:remove_iq_handler(ejabberd_sm, ServerHostB, ?NS_PUBSUB_OWNER); + false -> + ok end, ejabberd_hooks:delete(sm_remove_connection_hook, ServerHostB, ?MODULE, on_user_offline, 75), ejabberd_hooks:delete(disco_local_identity, ServerHostB, ?MODULE, disco_local_identity, 75), @@ -924,294 +1141,339 @@ code_change(_OldVsn, State, _Extra) -> %%-------------------------------------------------------------------- %%% Internal functions %%-------------------------------------------------------------------- -do_route(ServerHost, Access, Plugins, Host, From, To, Packet) -> - #xmlel{name = Name} = Packet, - LNode = exmpp_jid:prep_node(To), - LRes = exmpp_jid:prep_resource(To), - case {LNode, LRes} of - {undefined, undefined} -> - case Name of - 'iq' -> - case exmpp_iq:xmlel_to_iq(Packet) of - #iq{type = get, ns = ?NS_DISCO_INFO, - payload = SubEl, lang = Lang} -> - QAttrs = SubEl#xmlel.attrs, - Node = exmpp_xml:get_attribute_from_list_as_list(QAttrs, 'node', ""), - ServerHostB = list_to_binary(ServerHost), - Info = ejabberd_hooks:run_fold( - disco_info, ServerHostB, [], - [ServerHost, ?MODULE, <<>>, ""]), - Res = case iq_disco_info(Host, Node, From, Lang) of - {result, IQRes} -> - Result = #xmlel{ns = ?NS_DISCO_INFO, - name = 'query', attrs = QAttrs, - children = IQRes++Info}, - exmpp_iq:result(Packet, Result); - {error, Error} -> - exmpp_iq:error(Packet, Error) - end, - ejabberd_router:route(To, From, Res); - #iq{type = get, ns = ?NS_DISCO_ITEMS, - payload = SubEl} -> - QAttrs = SubEl#xmlel.attrs, - Node = exmpp_xml:get_attribute_from_list_as_list(QAttrs, 'node', ""), - Res = case iq_disco_items(Host, Node, From) of - {result, IQRes} -> - Result = #xmlel{ns = ?NS_DISCO_ITEMS, - name = 'query', attrs = QAttrs, - children = IQRes}, - exmpp_iq:result(Packet, Result); - {error, Error} -> - exmpp_iq:error(Packet, Error) - end, - ejabberd_router:route(To, From, Res); - #iq{type = IQType, ns = ?NS_PUBSUB, - lang = Lang, payload = SubEl} -> - Res = - case iq_pubsub(Host, ServerHost, From, IQType, SubEl, Lang, Access, Plugins) of - {result, []} -> - exmpp_iq:result(Packet); - {result, IQRes} -> - exmpp_iq:result(Packet, IQRes); - {error, Error} -> - exmpp_iq:error(Packet, Error) - end, - ejabberd_router:route(To, From, Res); - #iq{type = IQType, ns = ?NS_PUBSUB_OWNER, - lang = Lang, payload = SubEl} -> - Res = - case iq_pubsub_owner(Host, ServerHost, From, IQType, SubEl, Lang) of - {result, []} -> - exmpp_iq:result(Packet); - {result, IQRes} -> - exmpp_iq:result(Packet, IQRes); - {error, Error} -> - exmpp_iq:error(Packet, Error) - end, - ejabberd_router:route(To, From, Res); - #iq{type = get, ns = ?NS_VCARD = XMLNS, - lang = Lang} -> - VCard = #xmlel{ns = XMLNS, name = 'vCard', - children = iq_get_vcard(Lang)}, - Res = exmpp_iq:result(Packet, VCard), - ejabberd_router:route(To, From, Res); - #iq{type = set, ns = ?NS_ADHOC} = IQ -> - Res = case iq_command(Host, ServerHost, From, IQ, Access, Plugins) of - {error, Error} -> - exmpp_iq:error(Packet, Error); - {result, IQRes} -> - exmpp_iq:result(Packet, IQRes) - end, - ejabberd_router:route(To, From, Res); +-spec(do_route/7 :: + ( + ServerHost :: binary(), + Access :: atom(), + Plugins :: [Plugin::nodeType()], + Host :: hostPubsub(), + From :: jidEntity(), + To :: jidComponent(), + Packet :: #xmlel{name :: 'iq' | 'message' | 'presence'}) + -> any() + ). - #iq{} -> - Err = exmpp_iq:error(Packet, - 'feature-not-implemented'), - ejabberd_router:route(To, From, Err) +%%% +do_route(ServerHost, Access, Plugins, Host, From, To, #xmlel{name = 'iq'} = Packet) -> + case exmpp_iq:xmlel_to_iq(Packet) of + %% Service discovery : disco#info + #iq{type = 'get', ns = ?NS_DISCO_INFO, payload = #xmlel{attrs = Attrs}, lang = Lang} -> + NodeId = exmpp_xml:get_attribute_from_list(Attrs, 'node', <<>>), + Info = ejabberd_hooks:run_fold( + disco_info, ServerHost, [], + [ServerHost, ?MODULE, <<>>, ""]), + Res = case iq_disco_info(Host, NodeId, From, Lang) of + {result, IQRes} -> + Result = #xmlel{ns = ?NS_DISCO_INFO, + name = 'query', + attrs = Attrs, + children = IQRes++Info}, + exmpp_iq:result(Packet, Result); + {error, Error} -> + exmpp_iq:error(Packet, Error) + end, + ejabberd_router:route(To, From, Res); + %% Service discovery : disco#items + #iq{type = 'get', ns = ?NS_DISCO_ITEMS, payload = #xmlel{attrs = Attrs}} -> + NodeId = exmpp_xml:get_attribute_from_list(Attrs, 'node', <<>>), + Res = case iq_disco_items(Host, NodeId, From) of + {result, IQRes} -> + Result = #xmlel{ns = ?NS_DISCO_ITEMS, + name = 'query', + attrs = Attrs, + children = IQRes}, + exmpp_iq:result(Packet, Result); + {error, Error} -> + exmpp_iq:error(Packet, Error) + end, + ejabberd_router:route(To, From, Res); + %% pubsub + #iq{type = IQType, ns = ?NS_PUBSUB, lang = Lang, payload = #xmlel{} = SubEl} + when IQType == 'get' orelse IQType == 'set' -> + Res = case iq_pubsub(Host, ServerHost, From, IQType, SubEl, Lang, Access, Plugins) of + {result, []} -> exmpp_iq:result(Packet); + {result, IQRes} -> exmpp_iq:result(Packet, IQRes); + {error, Error} -> exmpp_iq:error(Packet, Error) + end, + ejabberd_router:route(To, From, Res); + %% pubsub#owner + #iq{type = IQType, ns = ?NS_PUBSUB_OWNER, lang = Lang, payload = #xmlel{} = SubEl} + when IQType == 'get' orelse IQType == 'set' -> + Res = case iq_pubsub_owner(Host, ServerHost, From, IQType, SubEl, Lang) of + {result, []} -> exmpp_iq:result(Packet); + {result, IQRes} -> exmpp_iq:result(Packet, IQRes); + {error, Error} -> exmpp_iq:error(Packet, Error) + end, + ejabberd_router:route(To, From, Res); %% TODO : add error handling + %% vCard + #iq{type = 'get', ns = ?NS_VCARD = XMLNS, lang = Lang} -> + VCard = #xmlel{ns = XMLNS, + name = 'vCard', + children = iq_get_vcard(Lang)}, + Res = exmpp_iq:result(Packet, VCard), + ejabberd_router:route(To, From, Res); + %% Ad hoc commands + #iq{type = 'set', ns = ?NS_ADHOC} = IQ -> + Res = case iq_command(Host, ServerHost, From, IQ, Access, Plugins) of + {error, Error} -> exmpp_iq:error(Packet, Error); + {result, IQRes} -> exmpp_iq:result(Packet, IQRes) + end, + ejabberd_router:route(To, From, Res); %%TODO : add error handling + %% Other + _ -> + Err = exmpp_iq:error(Packet, 'feature-not-implemented'), + ejabberd_router:route(To, From, Err) + end; + +%%% +do_route(ServerHost, _Access, _Plugins, Host, From, To, + #xmlel{name = 'message', children = Els} = Packet) -> + case exmpp_stanza:is_stanza_error(Packet) of + true -> + ok; + false -> + case exmpp_xml:remove_cdata_from_list(Els) of + %% + [#xmlel{name = 'x', ns = ?NS_DATA_FORMS}] -> + case find_authorization_response(Packet) of + none -> ok; + invalid -> + ejabberd_router:route(To, From, exmpp_message:error(Packet, 'bad-request')); + XFields -> + handle_authorization_response(Host, From, To, Packet, XFields) end; - 'message' -> - case exmpp_stanza:is_stanza_error(Packet) of - true -> + %% Pubsub vanilla + [#xmlel{name = 'pubsub', ns = ?NS_PUBSUB} = Pubsub] -> + case exmpp_xml:get_element(Pubsub, 'publish') of + undefined -> ok; - false -> - case exmpp_xml:remove_cdata_from_list(Packet#xmlel.children) of - [#xmlel{name = 'x', ns = ?NS_DATA_FORMS}] -> - case find_authorization_response(Packet) of - none -> + Publish -> + case exmpp_xml:get_element(Publish, 'item') of + undefined -> + ok; + #xmlel{attrs = Attrs, children = Els} = _Item -> + NodeId = exmpp_xml:get_attribute(Publish, 'node', <<>>), + ItemId = exmpp_xml:get_attribute_from_list(Attrs, 'id', <<>>), + case publish_item(Host, ServerHost, NodeId, From, ItemId, Els) of + {result, _} -> ok; - invalid -> - ejabberd_router:route(To, From, exmpp_message:error(Packet, 'bad-request')); - XFields -> - handle_authorization_response(Host, From, To, Packet, XFields) - end; - [#xmlel{name = 'pubsub', ns = ?NS_PUBSUB} = Pubsub] -> - case exmpp_xml:get_element(Pubsub, 'publish') of - undefined -> - ok; - Publish -> - Node = exmpp_xml:get_attribute(Publish, 'node', <<>>), - case exmpp_xml:get_element(Publish, 'item') of - undefined -> - ok; - Item -> - ItemId = exmpp_xml:get_attribute_as_list(Item, 'id', ""), - case publish_item(Host, ServerHost, Node, From, ItemId, Item#xmlel.children) of - {result, _} -> - ok; - {error, Reason} -> - ejabberd_router:route(To, From, exmpp_message:error(Packet, Reason)) - end - end - end; - _ -> - ok + {error, Reason} -> + ejabberd_router:route(To, From, exmpp_message:error(Packet, Reason)) + end end end; + %% Other _ -> ok - end; - _ -> - case exmpp_stanza:get_type(Packet) of - <<"error">> -> - ok; - <<"result">> -> - ok; - _ -> - Err = exmpp_stanza:reply_with_error(Packet, - 'item-not-found'), - ejabberd_router:route(To, From, Err) end + end; + +%% +do_route(_ServerHost, _Access, _Plugins, _Host, _From, _To, _Packet) -> + true. +%% Other cases ? + %do_route(_, _, _, _, From, To, Packet) -> + % case exmpp_stanza:get_type(Packet) of + % <<"error">> -> ok; + % <<"result">> -> ok; + % _ -> + % Err = exmpp_stanza:reply_with_error(Packet, 'item-not-found'), + % ejabberd_router:route(To, From, Err) + % end. + + +-spec(command_disco_info/3 :: + ( + Host :: hostPubsub(), %% Host::host() TODO : implement ad hoc commands for PEP + NodeId :: nodeId(), + From :: jidEntity()) + -> {result, Info::[#xmlel{name::'identity',ns::?NS_DISCO_INFO}]} + | {result, Info::[#xmlel{name::'identity',ns::?NS_DISCO_INFO} + |#xmlel{name::'feature',ns::?NS_DISCO_INFO}]} + ). + +command_disco_info(_Host, ?NS_ADHOC_b = _NodeId, _From) -> + {result, + [#xmlel{ns = ?NS_DISCO_INFO, + name = 'identity', + attrs = [?XMLATTR('category', <<"automation">>), + ?XMLATTR('type', <<"command-list">>)]}]}; +command_disco_info(_Host, ?NS_PUBSUB_GET_PENDING_b = _NodeId, _From) -> + {result, + % Identity + [#xmlel{ns = ?NS_DISCO_INFO, + name = 'identity', + attrs = [?XMLATTR('category', <<"automation">>), + ?XMLATTR('type', <<"command-node">>)]}, + % Features + #xmlel{ns = ?NS_DISCO_INFO, + name = 'feature', + attrs = [?XMLATTR('var', ?NS_ADHOC)]}]}. + + +-spec(node_disco_info/3 :: + ( + Host :: hostPubsub(), + NodeId :: nodeId(), + From :: jidEntity()) + -> {'result', [#xmlel{name::'identity',ns::?NS_DISCO_INFO} + |#xmlel{name::'feature',ns::?NS_DISCO_INFO}]} + | {'error', _} + ). + +node_disco_info(Host, NodeId, From) -> + Action = fun(#pubsub_node{type = Plugin, idx = NodeIdx}) -> + Types = case tree_call(Host, get_subnodes, [Host, NodeId, From]) of + [] -> ["leaf"]; + _ -> + case node_call(Plugin, get_items, [NodeIdx, From]) of + {result, []} -> ["collection"]; + {result, _} -> ["leaf", "collection"]; + _ -> [] + end + end, + %% TODO: add meta-data info (spec section 5.4) + {result, + %% Identities + [#xmlel{ns = ?NS_DISCO_INFO, + name = 'identity', + attrs = [?XMLATTR('category', <<"pubsub">>), + ?XMLATTR('type', Type)]} || Type <- Types ] + ++ + %% Features + [#xmlel{ns = ?NS_DISCO_INFO, + name = 'feature', + attrs = [?XMLATTR('var', ?NS_PUBSUB_b)]} | + [#xmlel{ns = ?NS_DISCO_INFO, + name = 'feature', + attrs = [?XMLATTR('var', list_to_binary(?NS_PUBSUB_s++"#"++Type))]} + || Type <- features(Plugin)]]} + end, + case transaction(Host, NodeId, Action, sync_dirty) of + {result, {_, Result}} -> {result, Result}; + Error -> Error end. -command_disco_info(_Host, ?NS_ADHOC_b, _From) -> - IdentityEl = - #xmlel{ns = ?NS_DISCO_INFO, name = 'identity', - attrs = [?XMLATTR('category', <<"automation">>), - ?XMLATTR('type', <<"command-list">>)]}, - {result, [IdentityEl]}; -command_disco_info(_Host, ?NS_PUBSUB_GET_PENDING_b, _From) -> - IdentityEl = - #xmlel{ns = ?NS_DISCO_INFO, name = 'identity', - attrs = [?XMLATTR('category', <<"automation">>), - ?XMLATTR('type', <<"command-node">>)]}, - FeaturesEl = #xmlel{ns = ?NS_DISCO_INFO, name = 'feature', - attrs = [?XMLATTR('var', ?NS_ADHOC)]}, - {result, [IdentityEl, FeaturesEl]}. -node_disco_info(Host, Node, From) -> - node_disco_info(Host, Node, From, true, true). -node_disco_info(Host, Node, From, Identity, Features) -> - Action = - fun(#pubsub_node{type = Type, idx = Nidx}) -> - I = case Identity of - false -> - []; - true -> - Types = - case tree_call(Host, get_subnodes, [Host, Node, From]) of - [] -> - ["leaf"]; %% No sub-nodes: it's a leaf node - _ -> - case node_call(Type, get_items, [Nidx, From]) of - {result, []} -> ["collection"]; - {result, _} -> ["leaf", "collection"]; - _ -> [] - end - end, - lists:map(fun(T) -> - #xmlel{ns = ?NS_DISCO_INFO, name = 'identity', attrs = [?XMLATTR('category', <<"pubsub">>), - ?XMLATTR('type', T)]} - end, Types) - end, - F = case Features of - false -> - []; - true -> - [#xmlel{ns = ?NS_DISCO_INFO, name = 'feature', attrs = [?XMLATTR('var', ?NS_PUBSUB_s)]} | - lists:map(fun(T) -> - #xmlel{ns = ?NS_DISCO_INFO, name = 'feature', attrs = [?XMLATTR('var', ?NS_PUBSUB_s++"#"++T)]} - end, features(Type))] - end, - %% TODO: add meta-data info (spec section 5.4) - {result, I ++ F} - end, - case transaction(Host, Node, Action, sync_dirty) of +-spec(iq_disco_info/4 :: + ( + Host :: hostPubsub(), + NodeId :: nodeId(), + From :: jidEntity(), + Lang :: binary()) + -> {'result', [#xmlel{name::'identity',ns::?NS_DISCO_INFO} + |#xmlel{name::'feature',ns::?NS_DISCO_INFO}]} + | {'error', _} + ). + +iq_disco_info(Host, <<>> = _NodeId, _From, Lang) -> + {result, + %% Identities + [#xmlel{ns = ?NS_DISCO_INFO, + name = 'identity', + attrs = [?XMLATTR('category', "pubsub"), + ?XMLATTR('type', "service"), + ?XMLATTR('name', translate:translate(Lang, "Publish-Subscribe"))]}, + %% Features + #xmlel{ns = ?NS_DISCO_INFO, + name = 'feature', + attrs = [?XMLATTR('var', ?NS_DISCO_INFO_b)]}, + #xmlel{ns = ?NS_DISCO_INFO, + name = 'feature', + attrs = [?XMLATTR('var', ?NS_DISCO_ITEMS_b)]}, + #xmlel{ns = ?NS_DISCO_INFO, + name = 'feature', + attrs = [?XMLATTR('var', ?NS_PUBSUB_b)]}, + #xmlel{ns = ?NS_DISCO_INFO, + name = 'feature', + attrs = [?XMLATTR('var', ?NS_ADHOC_b)]}, + #xmlel{ns = ?NS_DISCO_INFO, + name = 'feature', + attrs = [?XMLATTR('var', ?NS_VCARD_b)]}] + ++ + [#xmlel{ns = ?NS_DISCO_INFO, + name = 'feature', + attrs = [?XMLATTR('var', list_to_binary(?NS_PUBSUB_s++"#"++Feature))]} + || Feature <- features(Host, <<>>)]}; +iq_disco_info(Host, NodeId, From, _Lang) + when NodeId == ?NS_ADHOC_b orelse NodeId == ?NS_PUBSUB_GET_PENDING_b -> + command_disco_info(Host, NodeId, From); +iq_disco_info(Host, NodeId, From, _Lang) -> + node_disco_info(Host, NodeId, From). + + +-spec(iq_disco_items/3 :: + ( + Host :: hostPubsub(), + NodeId :: nodeId(), + From :: jidEntity()) + -> {'result', [] | [#xmlel{name::'item',ns::?NS_DISCO_ITEMS}]} + | {'error', _} + ). + +iq_disco_items(Host, <<>> = _NodeId, From) -> + case tree_action(Host, get_subnodes, [Host, <<>>, From]) of + Nodes when is_list(Nodes) -> + {result, lists:map( + fun(#pubsub_node{id = {_, SubNodeId}, options = Options}) -> + Attrs = + case get_option(Options, 'title') of + false -> + [?XMLATTR('jid', Host) | nodeAttr(SubNodeId)]; + Title -> + [?XMLATTR('jid', Host), ?XMLATTR('name', Title) | nodeAttr(SubNodeId)] + end, + #xmlel{ns = ?NS_DISCO_ITEMS, name = 'item', attrs = Attrs} + end, Nodes)}; + Other -> + Other + end; +iq_disco_items(Host, ?NS_ADHOC_b = _NodeId, _From) -> + %% TODO: support localization of this string + {result, + [#xmlel{ns = ?NS_DISCO_ITEMS, + name = 'item', + attrs = [?XMLATTR('jid', Host), + ?XMLATTR('node', ?NS_PUBSUB_GET_PENDING_b), + ?XMLATTR('name', "Get Pending")]}]}; +iq_disco_items(_Host, ?NS_PUBSUB_GET_PENDING_b = _NodeId, _From) -> + %% TODO + {result, []}; +iq_disco_items(Host, NodeId, From) -> + Action = fun(#pubsub_node{idx = NodeIdx, type = Type, options = Options, owners = Owners}) -> + NodeItems = case get_allowed_items_call(Host, NodeIdx, From, Type, Options, Owners) of + {result, R} -> R; + _ -> [] + end, + Nodes = lists:map( + fun(#pubsub_node{id = {_, SubNodeId}, options = SubOptions}) -> + Attrs = + case get_option(SubOptions, 'title') of + false -> + [?XMLATTR('jid', Host) | nodeAttr(SubNodeId)]; + Title -> + [?XMLATTR('jid', Host), ?XMLATTR('name', Title) | nodeAttr(SubNodeId)] + end, + #xmlel{ns = ?NS_DISCO_ITEMS, + name = 'item', + attrs = Attrs} + end, tree_call(Host, get_subnodes, [Host, NodeId, From])), + Items = lists:map( + fun(#pubsub_item{id = {RN, _}}) -> + {result, Name} = node_call(Type, get_item_name, [Host, NodeId, RN]), + #xmlel{ns = ?NS_DISCO_ITEMS, + name = 'item', + attrs = [?XMLATTR('jid', Host), + ?XMLATTR('name', Name)]} + end, NodeItems), + {result, Nodes ++ Items} + end, + case transaction(Host, NodeId, Action, sync_dirty) of {result, {_, Result}} -> {result, Result}; Other -> Other end. -iq_disco_info(Host, SNode, From, Lang) -> - [RealSNode|_] = case SNode of - [] -> [[]]; - _ -> string:tokens(SNode, "!") - end, - Node = string_to_node(RealSNode), - case Node of - <<>> -> - {result, - [#xmlel{ns = ?NS_DISCO_INFO, name = 'identity', attrs = - [?XMLATTR('category', "pubsub"), - ?XMLATTR('type', "service"), - ?XMLATTR('name', translate:translate(Lang, "Publish-Subscribe"))]}, - #xmlel{ns = ?NS_DISCO_INFO, name = 'feature', attrs = [?XMLATTR('var', ?NS_DISCO_INFO_s)]}, - #xmlel{ns = ?NS_DISCO_INFO, name = 'feature', attrs = [?XMLATTR('var', ?NS_DISCO_ITEMS_s)]}, - #xmlel{ns = ?NS_DISCO_INFO, name = 'feature', attrs = [?XMLATTR('var', ?NS_PUBSUB_s)]}, - #xmlel{ns = ?NS_DISCO_INFO, name = 'feature', attrs = [?XMLATTR('var', ?NS_ADHOC_s)]}, - #xmlel{ns = ?NS_DISCO_INFO, name = 'feature', attrs = [?XMLATTR('var', ?NS_VCARD_s)]}] ++ - lists:map(fun(Feature) -> - #xmlel{ns = ?NS_DISCO_INFO, name = 'feature', attrs = [?XMLATTR('var', ?NS_PUBSUB_s++"#"++Feature)]} - end, features(Host, Node))}; - ?NS_ADHOC_b -> - command_disco_info(Host, Node, From); - ?NS_PUBSUB_GET_PENDING_b -> - command_disco_info(Host, Node, From); - _ -> - node_disco_info(Host, Node, From) - end. -iq_disco_items(Host, [], From) -> - case tree_action(Host, get_subnodes, [Host, <<>>, From]) of - Nodes when is_list(Nodes) -> - {result, lists:map( - fun(#pubsub_node{id = {_, SubNode}, options = Options}) -> - Attrs = - case get_option(Options, title) of - false -> - [?XMLATTR('jid', Host) | nodeAttr(SubNode)]; - Title -> - [?XMLATTR('jid', Host), ?XMLATTR('name', Title) | nodeAttr(SubNode)] - end, - #xmlel{ns = ?NS_DISCO_ITEMS, name = 'item', attrs = Attrs} - end, Nodes)}; - Other -> - Other - end; -iq_disco_items(Host, ?NS_ADHOC_s, _From) -> - %% TODO: support localization of this string - CommandItems = [ - #xmlel{ns = ?NS_DISCO_ITEMS, name = 'item', - attrs = [?XMLATTR('jid', Host), - ?XMLATTR('node', ?NS_PUBSUB_GET_PENDING), - ?XMLATTR('name', "Get Pending") - ]}], - {result, CommandItems}; -iq_disco_items(_Host, ?NS_PUBSUB_GET_PENDING, _From) -> - CommandItems = [], - {result, CommandItems}; -iq_disco_items(Host, Item, From) -> - case string:tokens(Item, "!") of - [_SNode, _ItemId] -> - {result, []}; - [SNode] -> - Node = string_to_node(SNode), - Action = fun(#pubsub_node{idx = Nidx, type = Type, options = Options, owners = Owners}) -> - NodeItems = case get_allowed_items_call(Host, Nidx, From, Type, Options, Owners) of - {result, R} -> R; - _ -> [] - end, - Nodes = lists:map( - fun(#pubsub_node{id = {_, SubNode}, options = SubOptions}) -> - Attrs = - case get_option(SubOptions, title) of - false -> - [?XMLATTR('jid', Host) | nodeAttr(SubNode)]; - Title -> - [?XMLATTR('jid', Host), ?XMLATTR('name', Title) | nodeAttr(SubNode)] - end, - #xmlel{ns = ?NS_DISCO_ITEMS, name = 'item', attrs = Attrs} - end, tree_call(Host, get_subnodes, [Host, Node, From])), - Items = lists:map( - fun(#pubsub_item{id = {RN, _}}) -> - {result, Name} = node_call(Type, get_item_name, [Host, Node, RN]), - #xmlel{ns = ?NS_DISCO_ITEMS, name = 'item', attrs = [?XMLATTR('jid', Host), ?XMLATTR('name', Name)]} - end, NodeItems), - {result, Nodes ++ Items} - end, - case transaction(Host, Node, Action, sync_dirty) of - {result, {_, Result}} -> {result, Result}; - Other -> Other - end - end. get_allowed_items_call(Host, Nidx, From, Type, Options, Owners) -> AccessModel = get_option(Options, access_model), @@ -1221,134 +1483,172 @@ get_allowed_items_call(Host, Nidx, From, Type, Options, Owners) -> get_presence_and_roster_permissions(Host, From, Owners, AccessModel, AllowedGroups) -> if (AccessModel == presence) or (AccessModel == roster) -> - case Host of - {User, Server, _} -> - get_roster_info(User, Server, From, AllowedGroups); - _ -> - [{OUser, OServer, _}|_] = Owners, - get_roster_info(OUser, OServer, From, AllowedGroups) - end; - true -> - {true, true} + case Host of + {User, Server, _} -> + get_roster_info(User, Server, From, AllowedGroups); + _ -> + [{OUser, OServer, _}|_] = Owners, + get_roster_info(OUser, OServer, From, AllowedGroups) + end; + true -> + {true, true} end. -iq_sm(From, To, #iq{type = Type, payload = SubEl, ns = XMLNS, lang = Lang} = IQ_Rec) -> - ServerHost = exmpp_jid:prep_domain_as_list(To), - LOwner = jlib:short_prepd_bare_jid(To), - Res = case XMLNS of - ?NS_PUBSUB -> iq_pubsub(LOwner, ServerHost, From, Type, SubEl, Lang); - ?NS_PUBSUB_OWNER -> iq_pubsub_owner(LOwner, ServerHost, From, Type, SubEl, Lang) - end, - case Res of - {result, []} -> exmpp_iq:result(IQ_Rec); - {result, IQRes} -> exmpp_iq:result(IQ_Rec, IQRes); - {error, Error} -> exmpp_iq:error(IQ_Rec, Error) + +-spec(iq_sm/3 :: + ( + From :: jidEntity(), + To :: jidContact(), + IQ :: #iq{type::'get'|'set',ns::?NS_PUBSUB|?NS_PUBSUB_OWNER}) + -> #iq{type::'result'|'error',ns::?NS_PUBSUB|?NS_PUBSUB_OWNER} + ). + +iq_sm(From, #jid{node = U, domain = S, resource = undefined = R} = _To, + #iq{type = Type, payload = #xmlel{} = SubEl, ns = XMLNS, lang = Lang} = IQ) + when (Type == 'get' orelse Type == 'set') -> + Result = case XMLNS of + ?NS_PUBSUB -> iq_pubsub({U,S,R}, S, From, Type, SubEl, Lang); + ?NS_PUBSUB_OWNER -> iq_pubsub_owner({U,S,R}, S, From, Type, SubEl, Lang) + end, + case Result of + {result, []} -> exmpp_iq:result(IQ); + {result, IQResult} -> exmpp_iq:result(IQ, IQResult); + {error, Error} -> exmpp_iq:error(IQ, Error) end. +%%TODO : other IQ type and other cases + %iq_sm(_,_,IQ) -> exmpp_iq:result(IQ). + + +-spec(iq_get_vcard/1 :: + ( + Lang::binary()) + -> Vcard::[#xmlel{}] + ). iq_get_vcard(Lang) -> [#xmlel{ns = ?NS_VCARD, name = 'FN', children = [#xmlcdata{cdata = <<"ejabberd/mod_pubsub">>}]}, #xmlel{ns = ?NS_VCARD, name = 'URL', children = [#xmlcdata{cdata = list_to_binary(?EJABBERD_URI)}]}, #xmlel{ns = ?NS_VCARD, name = 'DESC', children = - [#xmlcdata{cdata = list_to_binary( - translate:translate(Lang, - "ejabberd Publish-Subscribe module") ++ - "\nCopyright (c) 2004-2010 ProcessOne")}]}]. + [#xmlcdata{cdata = list_to_binary( + translate:translate(Lang, + "ejabberd Publish-Subscribe module") ++ + "\nCopyright (c) 2004-2010 ProcessOne")}]}]. + + +-spec(iq_pubsub/6 :: + ( + Host :: host(), % hostPubsub() | hostPEP() + ServerHost :: binary(), + From :: jidEntity(), + IQType :: 'get' | 'set', + SubEl :: #xmlel{name::'pubsub',ns::?NS_PUBSUB}, + Lang :: binary()) + -> {'result', Result::[] | #xmlel{}} | {'error', _} + ). iq_pubsub(Host, ServerHost, From, IQType, SubEl, Lang) -> - iq_pubsub(Host, ServerHost, From, IQType, SubEl, Lang, all, plugins(ServerHost)). + iq_pubsub(Host, ServerHost, From, IQType, SubEl, Lang, 'all', plugins(ServerHost)). -iq_pubsub(Host, ServerHost, From, IQType, SubEl, Lang, Access, Plugins) -> - case exmpp_xml:remove_cdata_from_list(SubEl#xmlel.children) of - [#xmlel{name = Name, attrs = Attrs, children = Els} | Rest] -> + +-spec(iq_pubsub/8 :: + ( + Host :: host(), % hostPubsub() | hostPEP() + ServerHost :: binary(), + From :: jidEntity(), + IQType :: 'get' | 'set', + SubEl :: #xmlel{name::'pubsub',ns::?NS_PUBSUB}, + Lang :: binary(), + Access :: atom(), + Plugins :: [Plugin::nodeType()]) + -> {'result', Result::[] | #xmlel{}} | {'error', _} + ). + +iq_pubsub(Host, ServerHost, From, IQType, #xmlel{children = Els}, Lang, Access, Plugins) -> + case exmpp_xml:remove_cdata_from_list(Els) of + [#xmlel{name = Name, attrs = Attrs, children = SubEls} | Rest] -> %% Fix bug when owner retrieves his affiliations - Node = string_to_node(exmpp_xml:get_attribute_from_list_as_list(Attrs, 'node', "")), + NodeId = exmpp_xml:get_attribute_from_list(Attrs, 'node', <<>>), case {IQType, Name} of - {set, 'create'} -> + {'set', 'create'} -> Config = case Rest of - [#xmlel{name = 'configure', children = C}] -> C; - _ -> [] - end, + [#xmlel{name = 'configure', children = C}] -> C; + _ -> [] + end, %% Get the type of the node - Type = case exmpp_xml:get_attribute_from_list_as_list(Attrs, 'type', "") of - [] -> hd(Plugins); - T -> T - end, + Plugin = case exmpp_xml:get_attribute_from_list_as_list(Attrs, 'type', "") of + "" -> hd(Plugins); + T -> T + end, %% we use Plugins list matching because we do not want to allocate %% atoms for non existing type, this prevent atom allocation overflow - case lists:member(Type, Plugins) of + case lists:member(Plugin, Plugins) of false -> - {error, extended_error( - 'feature-not-implemented', - unsupported, "create-nodes")}; + {error, extended_error('feature-not-implemented', unsupported, "create-nodes")}; true -> - create_node(Host, ServerHost, Node, From, - Type, Access, Config) + create_node(Host, ServerHost, NodeId, From, Plugin, Access, Config) end; - {set, 'publish'} -> - case exmpp_xml:remove_cdata_from_list(Els) of + {'set', 'publish'} -> + case exmpp_xml:remove_cdata_from_list(SubEls) of [#xmlel{name = 'item', attrs = ItemAttrs, children = Payload}] -> - ItemId = exmpp_xml:get_attribute_from_list_as_list(ItemAttrs, 'id', ""), - publish_item(Host, ServerHost, Node, From, ItemId, Payload); + ItemId = exmpp_xml:get_attribute_from_list(ItemAttrs, 'id', <<>>), + publish_item(Host, ServerHost, NodeId, From, ItemId, + exmpp_xml:remove_cdata_from_list(Payload)); [] -> %% Publisher attempts to publish to persistent node with no item - {error, extended_error('bad-request', - "item-required")}; + {error, extended_error('bad-request', "item-required")}; _ -> %% Entity attempts to publish item with multiple payload elements or namespace does not match - {error, extended_error('bad-request', - "invalid-payload")} + {error, extended_error('bad-request', "invalid-payload")} end; - {set, 'retract'} -> - ForceNotify = case exmpp_xml:get_attribute_from_list_as_list(Attrs, 'notify', "") of - "1" -> true; - "true" -> true; - _ -> false + {'set', 'retract'} -> + ForceNotify = case exmpp_xml:get_attribute_from_list(Attrs, 'notify', <<>>) of + <<"1">> -> true; + <<"true">> -> true; + _ -> false end, - case exmpp_xml:remove_cdata_from_list(Els) of + case exmpp_xml:remove_cdata_from_list(SubEls) of [#xmlel{name = 'item', attrs = ItemAttrs}] -> - ItemId = exmpp_xml:get_attribute_from_list_as_list(ItemAttrs, 'id', ""), - delete_item(Host, Node, From, ItemId, ForceNotify); + ItemId = exmpp_xml:get_attribute_from_list(ItemAttrs, 'id', <<>>), + delete_item(Host, NodeId, From, ItemId, ForceNotify); _ -> %% Request does not specify an item - {error, extended_error('bad-request', - "item-required")} + {error, extended_error('bad-request', "item-required")} end; - {set, 'subscribe'} -> + {'set', 'subscribe'} -> Config = case Rest of - [#xmlel{name = 'options', children = C}] -> C; - _ -> [] - end, - JID = exmpp_xml:get_attribute_from_list_as_list(Attrs, 'jid', ""), - subscribe_node(Host, Node, From, JID, Config); - {set, 'unsubscribe'} -> - JID = exmpp_xml:get_attribute_from_list_as_list(Attrs, 'jid', ""), - SubId = exmpp_xml:get_attribute_from_list_as_list(Attrs, 'subid', ""), - unsubscribe_node(Host, Node, From, JID, SubId); - {get, 'items'} -> - MaxItems = exmpp_xml:get_attribute_from_list_as_list(Attrs, 'max_items', ""), - SubId = exmpp_xml:get_attribute_from_list_as_list(Attrs, 'subid', ""), + [#xmlel{name = 'options', children = C}] -> C; + _ -> [] + end, + JID = exmpp_xml:get_attribute_from_list(Attrs, 'jid', <<>>), + subscribe_node(Host, NodeId, From, JID, Config); + {'set', 'unsubscribe'} -> + JID = exmpp_xml:get_attribute_from_list(Attrs, 'jid', <<>>), + SubId = exmpp_xml:get_attribute_from_list(Attrs, 'subid', <<>>), + unsubscribe_node(Host, NodeId, From, JID, SubId); + {'get', 'items'} -> + MaxItems = exmpp_xml:get_attribute_from_list(Attrs, 'max_items', <<>>), + SubId = exmpp_xml:get_attribute_from_list(Attrs, 'subid', <<>>), ItemIds = lists:foldl(fun - (#xmlel{name = 'item', attrs = ItemAttrs}, Acc) -> - case exmpp_xml:get_attribute_from_list_as_list(ItemAttrs, 'id', "") of - "" -> Acc; - ItemId -> [ItemId|Acc] - end; - (_, Acc) -> - Acc - end, [], exmpp_xml:remove_cdata_from_list(Els)), - get_items(Host, Node, From, SubId, MaxItems, ItemIds); - {get, 'subscriptions'} -> - get_subscriptions(Host, Node, From, Plugins); - {get, 'affiliations'} -> + (#xmlel{name = 'item', attrs = ItemAttrs}, Acc) -> + case exmpp_xml:get_attribute_from_list(ItemAttrs, 'id', <<>>) of + <<>> -> Acc; + ItemId -> [ItemId|Acc] + end; + (_, Acc) -> Acc + end, [], exmpp_xml:remove_cdata_from_list(SubEls)), + get_items(Host, NodeId, From, SubId, MaxItems, ItemIds); + {'get', 'subscriptions'} -> + get_subscriptions(Host, NodeId, From, Plugins); + {'get', 'affiliations'} -> get_affiliations(Host, From, Plugins); - {get, 'options'} -> - SubId = exmpp_xml:get_attribute_from_list_as_list(Attrs, 'subid', ""), - JID = exmpp_xml:get_attribute_from_list_as_list(Attrs, 'jid', ""), - get_options(Host, Node, JID, SubId, Lang); - {set, 'options'} -> - SubId = exmpp_xml:get_attribute_from_list_as_list(Attrs, 'subid', ""), - JID = exmpp_xml:get_attribute_from_list_as_list(Attrs, 'jid', ""), - set_options(Host, Node, JID, SubId, Els); + {'get', 'options'} -> + SubId = exmpp_xml:get_attribute_from_list(Attrs, 'subid', <<>>), + JID = exmpp_xml:get_attribute_from_list(Attrs, 'jid', <<>>), + get_options(Host, NodeId, JID, SubId, Lang); + {'set', 'options'} -> + SubId = exmpp_xml:get_attribute_from_list(Attrs, 'subid', <<>>), + JID = exmpp_xml:get_attribute_from_list(Attrs, 'jid', <<>>), + set_options(Host, NodeId, JID, SubId, SubEls); _ -> {error, 'feature-not-implemented'} end; @@ -1357,31 +1657,41 @@ iq_pubsub(Host, ServerHost, From, IQType, SubEl, Lang, Access, Plugins) -> {error, 'bad-request'} end. -iq_pubsub_owner(Host, ServerHost, From, IQType, SubEl, Lang) -> - SubEls = SubEl#xmlel.children, - Action = exmpp_xml:remove_cdata_from_list(SubEls), - case Action of - [#xmlel{name = Name, attrs = Attrs, children = Els}] -> - Node = string_to_node(exmpp_xml:get_attribute_from_list_as_list(Attrs, 'node', "")), + +-spec(iq_pubsub_owner/6 :: + ( + Host :: host(), % hostPubsub() | hostPEP() + ServerHost :: binary(), + From :: jidEntity(), + IQType :: 'get' | 'set', + SubEl :: #xmlel{name::'pubsub',ns::?NS_PUBSUB_OWNER}, + Lang :: binary()) + -> {'result', Result::[] | #xmlel{}} | {'error', _} + ). + +iq_pubsub_owner(Host, ServerHost, From, IQType, #xmlel{children = Els}, Lang) -> + case Action = exmpp_xml:remove_cdata_from_list(Els) of + [#xmlel{name = Name, attrs = Attrs, children = SubEls}] -> + NodeId = exmpp_xml:get_attribute_from_list(Attrs, 'node', <<>>), case {IQType, Name} of - {get, 'configure'} -> - get_configure(Host, ServerHost, Node, From, Lang); - {set, 'configure'} -> - set_configure(Host, Node, From, Els, Lang); - {get, 'default'} -> - get_default(Host, Node, From, Lang); - {set, 'delete'} -> - delete_node(Host, Node, From); - {set, 'purge'} -> - purge_node(Host, Node, From); - {get, 'subscriptions'} -> - get_subscriptions(Host, Node, From); - {set, 'subscriptions'} -> - set_subscriptions(Host, Node, From, exmpp_xml:remove_cdata_from_list(Els)); - {get, 'affiliations'} -> - get_affiliations(Host, Node, From); - {set, 'affiliations'} -> - set_affiliations(Host, Node, From, exmpp_xml:remove_cdata_from_list(Els)); + {'get', 'configure'} -> + get_configure(Host, ServerHost, NodeId, From, Lang); + {'set', 'configure'} -> + set_configure(Host, NodeId, From, SubEls, Lang); + {'get', 'default'} -> + get_default(Host, NodeId, From, Lang); + {'set', 'delete'} -> + delete_node(Host, NodeId, From); + {'set', 'purge'} -> + purge_node(Host, NodeId, From); + {'get', 'subscriptions'} -> + get_subscriptions(Host, NodeId, From); + {'set', 'subscriptions'} -> + set_subscriptions(Host, NodeId, From, exmpp_xml:remove_cdata_from_list(SubEls)); + {'get', 'affiliations'} -> + get_affiliations(Host, NodeId, From); + {'set', 'affiliations'} -> + set_affiliations(Host, NodeId, From, exmpp_xml:remove_cdata_from_list(SubEls)); _ -> {error, 'feature-not-implemented'} end; @@ -1390,34 +1700,60 @@ iq_pubsub_owner(Host, ServerHost, From, IQType, SubEl, Lang) -> {error, 'bad-request'} end. + +-spec(iq_command/6 :: + ( + Host :: hostPubsub(), %% TODO : ad hoc commands for PEP + ServerHost :: binary(), + From :: jidEntity(), + IQ :: #iq{ + type :: 'set', + ns :: ?NS_ADHOC}, + Access :: atom(), + Plugins :: [Plugin::nodeType()]) + -> {'result', [Result::#xmlel{ns::?NS_ADHOC,name::'command'}]} + | {'error', Error::_} + ). + iq_command(Host, ServerHost, From, IQ, Access, Plugins) -> case adhoc:parse_request(IQ) of - Req when is_record(Req, adhoc_request) -> - case adhoc_request(Host, ServerHost, From, Req, Access, Plugins) of - Resp when is_record(Resp, adhoc_response) -> - {result, [adhoc:produce_response(Req, Resp)]}; + #adhoc_request{} = Request -> + case adhoc_request(Host, ServerHost, From, Request, Access, Plugins) of + #adhoc_response{} = Response -> + {result, [adhoc:produce_response(Request, Response)]}; Error -> Error end; - Err -> - Err + Error -> + Error end. %% @doc

Processes an Ad Hoc Command.

+-spec(adhoc_request/6 :: + ( + Host :: hostPubsub(), %% TODO : ad hoc commands for PEP + ServerHost :: binary(), + From :: jidEntity(), + Request :: #adhoc_request{}, + Access :: atom(), + Plugins :: [Plugin::nodeType()]) + -> #adhoc_response{} | {'error', Error::_} + ). + adhoc_request(Host, _ServerHost, Owner, #adhoc_request{node = ?NS_PUBSUB_GET_PENDING, lang = Lang, action = "execute", xdata = false}, - _Access, Plugins) -> + _Access, Plugins) -> send_pending_node_form(Host, Owner, Lang, Plugins); adhoc_request(Host, _ServerHost, Owner, #adhoc_request{node = ?NS_PUBSUB_GET_PENDING, action = "execute", xdata = XData}, - _Access, _Plugins) -> + _Access, _Plugins) -> ParseOptions = case XData of - #xmlel{name = 'x'} = XEl -> + #xmlel{name = 'x'} = XEl -> case jlib:parse_xdata_submit(XEl) of invalid -> {error, exmpp_stanza:error(?NS_JABBER_CLIENT, 'bad-request')}; @@ -1470,16 +1806,16 @@ send_pending_node_form(Host, Owner, _Lang, Plugins) -> XOpts = lists:map(fun (Node) -> #xmlel{ns = ?NS_DATA_FORMS, name='option', children = [ - #xmlel{ns = ?NS_DATA_FORMS, name = 'value', - children = [ - exmpp_xml:cdata(node_to_string(Node))]}]} + #xmlel{ns = ?NS_DATA_FORMS, name = 'value', + children = [ + exmpp_xml:cdata(node_to_string(Node))]}]} end, get_pending_nodes(Host, Owner, Ps)), XForm = #xmlel{ns = ?NS_DATA_FORMS, name ='x', attrs = [?XMLATTR('type', <<"form">>)], - children = [ - #xmlel{ns = ?NS_DATA_FORMS, name = 'field', - attrs = [?XMLATTR('type', <<"list-single">>), - ?XMLATTR('var', <<"pubsub#node">>)], - children = lists:usort(XOpts)}]}, + children = [ + #xmlel{ns = ?NS_DATA_FORMS, name = 'field', + attrs = [?XMLATTR('type', <<"list-single">>), + ?XMLATTR('var', <<"pubsub#node">>)], + children = lists:usort(XOpts)}]}, #adhoc_response{status = executing, defaultaction = "execute", elements = [XForm]} @@ -1522,14 +1858,14 @@ send_pending_auth_events(Host, Node, Owner) -> case transaction(Host, Node, Action, sync_dirty) of {result, {N, Subscriptions}} -> lists:foreach(fun({J, pending, _SubId}) -> - {U, S, R} = J, - send_authorization_request(N, exmpp_jid:make(U,S,R)); - ({J, pending}) -> - {U, S, R} = J, - send_authorization_request(N, exmpp_jid:make(U,S,R)); - (_) -> - ok - end, Subscriptions), + {U, S, R} = J, + send_authorization_request(N, exmpp_jid:make(U,S,R)); + ({J, pending}) -> + {U, S, R} = J, + send_authorization_request(N, exmpp_jid:make(U,S,R)); + (_) -> + ok + end, Subscriptions), #adhoc_response{}; Err -> Err @@ -1541,33 +1877,33 @@ send_authorization_request(#pubsub_node{owners = Owners, id = {Host, Node}}, Sub Lang = <<"en">>, %% TODO fix {U, S, R} = Subscriber, Stanza = #xmlel{ns = ?NS_JABBER_CLIENT, name = 'message', children = - [#xmlel{ns = ?NS_DATA_FORMS, name = 'x', attrs = [?XMLATTR('type', <<"form">>)], children = - [#xmlel{ns = ?NS_DATA_FORMS, name = 'title', children = - [#xmlcdata{cdata = list_to_binary(translate:translate(Lang, "PubSub subscriber request"))}]}, - #xmlel{ns = ?NS_DATA_FORMS, name = 'instructions', children = - [#xmlcdata{cdata = list_to_binary(translate:translate(Lang, "Choose whether to approve this entity's subscription."))}]}, - #xmlel{ns = ?NS_DATA_FORMS, name = 'field', attrs = - [?XMLATTR('var', <<"FORM_TYPE">>), ?XMLATTR('type', <<"hidden">>)], children = - [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = [#xmlcdata{cdata = list_to_binary(?NS_PUBSUB_SUBSCRIBE_AUTH_s)}]}]}, - #xmlel{ns = ?NS_DATA_FORMS, name = 'field', attrs = - [?XMLATTR('var', <<"pubsub#node">>), ?XMLATTR('type', <<"text-single">>), - ?XMLATTR('label', translate:translate(Lang, "Node ID"))], children = - [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = - [#xmlcdata{cdata = Node}]}]}, - #xmlel{ns = ?NS_DATA_FORMS, name = 'field', attrs = [?XMLATTR('var', <<"pubsub#subscriber_jid">>), - ?XMLATTR('type', <<"jid-single">>), - ?XMLATTR('label', translate:translate(Lang, "Subscriber Address"))], children = - [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = - [#xmlcdata{cdata = exmpp_jid:to_binary(U, S, R)}]}]}, - #xmlel{ns = ?NS_DATA_FORMS, name = 'field', attrs = - [?XMLATTR('var', <<"pubsub#allow">>), - ?XMLATTR('type', <<"boolean">>), - ?XMLATTR('label', translate:translate(Lang, "Allow this Jabber ID to subscribe to this pubsub node?"))], children = - [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = [#xmlcdata{cdata = <<"false">>}]}]}]}]}, + [#xmlel{ns = ?NS_DATA_FORMS, name = 'x', attrs = [?XMLATTR('type', <<"form">>)], children = + [#xmlel{ns = ?NS_DATA_FORMS, name = 'title', children = + [#xmlcdata{cdata = list_to_binary(translate:translate(Lang, "PubSub subscriber request"))}]}, + #xmlel{ns = ?NS_DATA_FORMS, name = 'instructions', children = + [#xmlcdata{cdata = list_to_binary(translate:translate(Lang, "Choose whether to approve this entity's subscription."))}]}, + #xmlel{ns = ?NS_DATA_FORMS, name = 'field', attrs = + [?XMLATTR('var', <<"FORM_TYPE">>), ?XMLATTR('type', <<"hidden">>)], children = + [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = [#xmlcdata{cdata = list_to_binary(?NS_PUBSUB_SUBSCRIBE_AUTH_s)}]}]}, + #xmlel{ns = ?NS_DATA_FORMS, name = 'field', attrs = + [?XMLATTR('var', <<"pubsub#node">>), ?XMLATTR('type', <<"text-single">>), + ?XMLATTR('label', translate:translate(Lang, "Node ID"))], children = + [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = + [#xmlcdata{cdata = Node}]}]}, + #xmlel{ns = ?NS_DATA_FORMS, name = 'field', attrs = [?XMLATTR('var', <<"pubsub#subscriber_jid">>), + ?XMLATTR('type', <<"jid-single">>), + ?XMLATTR('label', translate:translate(Lang, "Subscriber Address"))], children = + [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = + [#xmlcdata{cdata = exmpp_jid:to_binary(U, S, R)}]}]}, + #xmlel{ns = ?NS_DATA_FORMS, name = 'field', attrs = + [?XMLATTR('var', <<"pubsub#allow">>), + ?XMLATTR('type', <<"boolean">>), + ?XMLATTR('label', translate:translate(Lang, "Allow this Jabber ID to subscribe to this pubsub node?"))], children = + [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = [#xmlcdata{cdata = <<"false">>}]}]}]}]}, lists:foreach(fun(Owner) -> - {U, S, R} = Owner, - ejabberd_router:route(service_jid(Host), exmpp_jid:make(U, S, R), Stanza) - end, Owners). + {U, S, R} = Owner, + ejabberd_router:route(service_jid(Host), exmpp_jid:make(U, S, R), Stanza) + end, Owners). find_authorization_response(Packet) -> Els = Packet#xmlel.children, @@ -1608,11 +1944,11 @@ send_authorization_approval(Host, JID, SNode, Subscription) -> S -> [?XMLATTR('subscription', subscription_to_string(S))] end, Stanza = event_stanza( - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'subscription', attrs = - [?XMLATTR('jid', exmpp_jid:to_binary(JID)) | nodeAttr(SNode)] ++ SubAttrs - }]), + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'subscription', attrs = + [?XMLATTR('jid', exmpp_jid:to_binary(JID)) | nodeAttr(SNode)] ++ SubAttrs + }]), ejabberd_router:route(service_jid(Host), JID, Stanza). - + handle_authorization_response(Host, From, To, Packet, XFields) -> case {lists:keysearch("pubsub#node", 1, XFields), lists:keysearch("pubsub#subscriber_jid", 1, XFields), @@ -1634,15 +1970,15 @@ handle_authorization_response(Host, From, To, Packet, XFields) -> {error, 'forbidden'}; true -> update_auth(Host, SNode, Type, Nidx, - Subscriber, Allow, - Subscriptions) + Subscriber, Allow, + Subscriptions) end end, case transaction(Host, Node, Action, sync_dirty) of {error, Error} -> ejabberd_router:route( - To, From, - exmpp_stanza:reply_with_error(Packet, Error)); + To, From, + exmpp_stanza:reply_with_error(Packet, Error)); {result, _} -> %% XXX: notify about subscription state change, section 12.11 ok @@ -1656,7 +1992,7 @@ handle_authorization_response(Host, From, To, Packet, XFields) -> update_auth(Host, Node, Type, Nidx, Subscriber, Allow, Subscriptions) -> Subscription = lists:filter(fun({pending, _}) -> true; - (_) -> false + (_) -> false end, Subscriptions), case Subscription of [{pending, SubId}] -> %% TODO does not work if several pending @@ -1675,9 +2011,9 @@ update_auth(Host, Node, Type, Nidx, Subscriber, -define(XFIELD(Type, Label, Var, Val), #xmlel{ns = ?NS_DATA_FORMS, name = 'field', attrs = [?XMLATTR('type', Type), - ?XMLATTR('label', translate:translate(Lang, Label)), - ?XMLATTR('var', Var)], children = - [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = [#xmlcdata{cdata = list_to_binary(Val)}]}]}). + ?XMLATTR('label', translate:translate(Lang, Label)), + ?XMLATTR('var', Var)], children = + [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = [#xmlcdata{cdata = list_to_binary(Val)}]}]}). -define(BOOLXFIELD(Label, Var, Val), ?XFIELD("boolean", Label, Var, @@ -1695,38 +2031,38 @@ update_auth(Host, Node, Type, Nidx, Subscriber, attrs = [?XMLATTR('type', <<"text-multi">>), ?XMLATTR('label', translate:translate(Lang, Label)), ?XMLATTR('var', Var) - ], - children = [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', - children = [?XMLCDATA(V)]} || V <- Vals]}). + ], + children = [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', + children = [?XMLCDATA(V)]} || V <- Vals]}). -define(XFIELDOPT(Type, Label, Var, Val, Opts), #xmlel{ns = ?NS_DATA_FORMS, name = 'field', attrs = [?XMLATTR('type', Type), - ?XMLATTR('label', translate:translate(Lang, Label)), - ?XMLATTR('var', Var)], children = - lists:map(fun(Opt) -> - #xmlel{ns = ?NS_DATA_FORMS, name = 'option', children = - [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = - [#xmlcdata{cdata = list_to_binary(Opt)}]}]} - end, Opts) ++ - [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = [#xmlcdata{cdata = list_to_binary(Val)}]}]}). + ?XMLATTR('label', translate:translate(Lang, Label)), + ?XMLATTR('var', Var)], children = + lists:map(fun(Opt) -> + #xmlel{ns = ?NS_DATA_FORMS, name = 'option', children = + [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = + [#xmlcdata{cdata = list_to_binary(Opt)}]}]} + end, Opts) ++ + [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = [#xmlcdata{cdata = list_to_binary(Val)}]}]}). -define(LISTXFIELD(Label, Var, Val, Opts), ?XFIELDOPT("list-single", Label, Var, Val, Opts)). -define(LISTMXFIELD(Label, Var, Vals, Opts), #xmlel{ns = ?NS_DATA_FORMS, name = 'field', attrs = [?XMLATTR('type', <<"list-multi">>), - ?XMLATTR('label', translate:translate(Lang, Label)), - ?XMLATTR('var', Var)], children = - lists:map(fun(Opt) -> - #xmlel{ns = ?NS_DATA_FORMS, name = 'option', children = - [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = - [#xmlcdata{cdata = list_to_binary(Opt)}]}]} - end, Opts) ++ - lists:map(fun(Val) -> - #xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = - [#xmlcdata{cdata = list_to_binary(Val)}]} - end, Vals) - }). + ?XMLATTR('label', translate:translate(Lang, Label)), + ?XMLATTR('var', Var)], children = + lists:map(fun(Opt) -> + #xmlel{ns = ?NS_DATA_FORMS, name = 'option', children = + [#xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = + [#xmlcdata{cdata = list_to_binary(Opt)}]}]} + end, Opts) ++ + lists:map(fun(Val) -> + #xmlel{ns = ?NS_DATA_FORMS, name = 'value', children = + [#xmlcdata{cdata = list_to_binary(Val)}]} + end, Vals) + }). %% @spec (Host::host(), ServerHost::host(), Node::pubsubNode(), Owner::jid(), NodeType::nodeType()) -> %% {error, Reason::stanzaError()} | @@ -1759,9 +2095,9 @@ create_node(Host, ServerHost, <<>>, Owner, Type, Access, Configuration) -> {result, []} -> {result, [#xmlel{ns = ?NS_PUBSUB, name = 'pubsub', children = - [#xmlel{ns = ?NS_PUBSUB, name = 'create', attrs = nodeAttr(NewNode)}]}]}; + [#xmlel{ns = ?NS_PUBSUB, name = 'create', attrs = nodeAttr(NewNode)}]}]}; Error -> - Error + Error end; false -> %% Service does not support instant nodes @@ -1795,13 +2131,13 @@ create_node(Host, ServerHost, Node, Owner, GivenType, Access, Configuration) -> fun() -> SNode = node_to_string(Node), Parent = case node_call(Type, node_to_path, [Node]) of - {result, [SNode]} -> <<>>; - {result, Path} -> element(2, node_call(Type, path_to_node, [lists:sublist(Path, length(Path)-1)])) - end, + {result, [SNode]} -> <<>>; + {result, Path} -> element(2, node_call(Type, path_to_node, [lists:sublist(Path, length(Path)-1)])) + end, Parents = case Parent of - <<>> -> []; - _ -> [Parent] - end, + <<>> -> []; + _ -> [Parent] + end, case node_call(Type, create_node_permission, [Host, ServerHost, Node, Parent, Owner, Access]) of {result, true} -> case tree_call(Host, create_node, [Host, Node, Type, Owner, NodeOptions, Parents]) of @@ -1825,7 +2161,7 @@ create_node(Host, ServerHost, Node, Owner, GivenType, Access, Configuration) -> end end, Reply = #xmlel{ns = ?NS_PUBSUB, name = 'pubsub', children = - [#xmlel{ns = ?NS_PUBSUB, name = 'create', attrs = nodeAttr(Node)}]}, + [#xmlel{ns = ?NS_PUBSUB, name = 'create', attrs = nodeAttr(Node)}]}, case transaction(CreateNode, transaction) of {result, {NodeId, SubsByDepth, {Result, broadcast}}} -> broadcast_created_node(Host, Node, NodeId, Type, NodeOptions, SubsByDepth), @@ -1865,31 +2201,31 @@ delete_node(_Host, <<>>, _Owner) -> {error, 'not-allowed'}; delete_node(Host, Node, Owner) -> Action = fun(#pubsub_node{type = Type, idx = Nidx}) -> - case node_call(Type, get_affiliation, [Nidx, Owner]) of - {result, owner} -> - ParentTree = tree_call(Host, get_parentnodes_tree, [Host, Node, service_jid(Host)]), - SubsByDepth = [{Depth, [{N, get_node_subs(N)} || N <- Nodes]} || {Depth, Nodes} <- ParentTree], - Removed = tree_call(Host, delete_node, [Host, Node]), - case node_call(Type, delete_node, [Removed]) of - {result, Res} -> {result, {SubsByDepth, Res}}; - Error -> Error - end; - _ -> - %% Entity is not an owner - {error, 'forbidden'} - end + case node_call(Type, get_affiliation, [Nidx, Owner]) of + {result, owner} -> + ParentTree = tree_call(Host, get_parentnodes_tree, [Host, Node, service_jid(Host)]), + SubsByDepth = [{Depth, [{N, get_node_subs(N)} || N <- Nodes]} || {Depth, Nodes} <- ParentTree], + Removed = tree_call(Host, delete_node, [Host, Node]), + case node_call(Type, delete_node, [Removed]) of + {result, Res} -> {result, {SubsByDepth, Res}}; + Error -> Error + end; + _ -> + %% Entity is not an owner + {error, 'forbidden'} + end end, Reply = [], case transaction(Host, Node, Action, transaction) of {result, {_, {SubsByDepth, {Result, broadcast, Removed}}}} -> lists:foreach(fun({RNode, _RSubscriptions}) -> - {RH, RN} = RNode#pubsub_node.id, - Nidx = RNode#pubsub_node.idx, - Type = RNode#pubsub_node.type, - Options = RNode#pubsub_node.options, - broadcast_removed_node(RH, RN, Nidx, Type, Options, SubsByDepth), - unset_cached_item(RH, Nidx) - end, Removed), + {RH, RN} = RNode#pubsub_node.id, + Nidx = RNode#pubsub_node.idx, + Type = RNode#pubsub_node.type, + Options = RNode#pubsub_node.options, + broadcast_removed_node(RH, RN, Nidx, Type, Options, SubsByDepth), + unset_cached_item(RH, Nidx) + end, Removed), case Result of default -> {result, Reply}; _ -> {result, Result} @@ -1931,46 +2267,46 @@ delete_node(Host, Node, Owner) -> %% subscribe_node(Host, Node, From, JID, Configuration) -> SubOpts = case pubsub_subscription:parse_options_xform(Configuration) of - {result, GoodSubOpts} -> GoodSubOpts; - _ -> invalid - end, + {result, GoodSubOpts} -> GoodSubOpts; + _ -> invalid + end, Subscriber = try - jlib:short_prepd_jid(exmpp_jid:parse(JID)) - catch - _:_ -> - {undefined, undefined, undefined} - end, + jlib:short_prepd_jid(exmpp_jid:parse(JID)) + catch + _:_ -> + {undefined, undefined, undefined} + end, Action = fun(#pubsub_node{options = Options, owners = Owners, type = Type, idx = Nidx}) -> - Features = features(Type), - SubscribeFeature = lists:member("subscribe", Features), - OptionsFeature = lists:member("subscription-options", Features), - HasOptions = not (SubOpts == []), - SubscribeConfig = get_option(Options, subscribe), - AccessModel = get_option(Options, access_model), - SendLast = get_option(Options, send_last_published_item), - AllowedGroups = get_option(Options, roster_groups_allowed, []), - {PresenceSubscription, RosterGroup} = get_presence_and_roster_permissions(Host, Subscriber, Owners, AccessModel, AllowedGroups), - if - not SubscribeFeature -> - %% Node does not support subscriptions - {error, extended_error('feature-not-implemented', unsupported, "subscribe")}; - not SubscribeConfig -> - %% Node does not support subscriptions - {error, extended_error('feature-not-implemented', unsupported, "subscribe")}; - HasOptions andalso not OptionsFeature -> - %% Node does not support subscription options - {error, extended_error('feature-not-implemented', unsupported, "subscription-options")}; - SubOpts == invalid -> - %% Passed invalit options submit form - {error, extended_error('bad-request', "invalid-options")}; - true -> - node_call(Type, subscribe_node, - [Nidx, From, Subscriber, + Features = features(Type), + SubscribeFeature = lists:member("subscribe", Features), + OptionsFeature = lists:member("subscription-options", Features), + HasOptions = not (SubOpts == []), + SubscribeConfig = get_option(Options, subscribe), + AccessModel = get_option(Options, access_model), + SendLast = get_option(Options, send_last_published_item), + AllowedGroups = get_option(Options, roster_groups_allowed, []), + {PresenceSubscription, RosterGroup} = get_presence_and_roster_permissions(Host, Subscriber, Owners, AccessModel, AllowedGroups), + if + not SubscribeFeature -> + %% Node does not support subscriptions + {error, extended_error('feature-not-implemented', unsupported, "subscribe")}; + not SubscribeConfig -> + %% Node does not support subscriptions + {error, extended_error('feature-not-implemented', unsupported, "subscribe")}; + HasOptions andalso not OptionsFeature -> + %% Node does not support subscription options + {error, extended_error('feature-not-implemented', unsupported, "subscription-options")}; + SubOpts == invalid -> + %% Passed invalit options submit form + {error, extended_error('bad-request', "invalid-options")}; + true -> + node_call(Type, subscribe_node, + [Nidx, From, Subscriber, AccessModel, SendLast, PresenceSubscription, RosterGroup, SubOpts]) - end - end, + end + end, Reply = fun(Subscription) -> %% TODO, this is subscription-notification, should depends on node features SubAttrs = case Subscription of @@ -1983,7 +2319,7 @@ subscribe_node(Host, Node, From, JID, Configuration) -> Fields = [ ?XMLATTR('jid', JID) | SubAttrs], #xmlel{ns = ?NS_PUBSUB, name = 'pubsub', children = - [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', attrs = Fields}]} + [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', attrs = Fields}]} end, case transaction(Host, Node, Action, sync_dirty) of {result, {TNode, {Result, subscribed, SubId, send_last}}} -> @@ -2034,15 +2370,15 @@ subscribe_node(Host, Node, From, JID, Configuration) -> %% unsubscribe_node(Host, Node, From, JID, SubId) when is_list(JID) -> Subscriber = try jlib:short_prepd_jid(exmpp_jid:parse(JID)) - catch - _:_ -> - {undefined, undefined, undefined} - end, + catch + _:_ -> + {undefined, undefined, undefined} + end, unsubscribe_node(Host, Node, From, Subscriber, SubId); unsubscribe_node(Host, Node, From, Subscriber, SubId) -> Action = fun(#pubsub_node{type = Type, idx = Nidx}) -> - node_call(Type, unsubscribe_node, [Nidx, From, Subscriber, SubId]) - end, + node_call(Type, unsubscribe_node, [Nidx, From, Subscriber, SubId]) + end, case transaction(Host, Node, Action, sync_dirty) of {result, {TNode, default}} -> notify_owners(get_option(TNode#pubsub_node.options, notify_sub), Subscriber, Host, Node, TNode#pubsub_node.owners, "none"), @@ -2073,61 +2409,61 @@ publish_item(Host, ServerHost, Node, Publisher, "", Payload) -> publish_item(Host, ServerHost, Node, Publisher, uniqid(), Payload); publish_item(Host, ServerHost, Node, Publisher, ItemId, Payload) -> Action = fun(#pubsub_node{options = Options, type = Type, idx = Nidx}) -> - Features = features(Type), - PublishFeature = lists:member("publish", Features), - PublishModel = get_option(Options, publish_model), - MaxItems = max_items(Host, Options), - DeliverPayloads = get_option(Options, deliver_payloads), - PersistItems = get_option(Options, persist_items), - {PayloadCount, PayloadNS} = payload_els_ns(Payload), - PayloadSize = size(term_to_binary(Payload)), - PayloadMaxSize = get_option(Options, max_payload_size), - InvalidNS = case get_option(Options, type) of - false -> false; - [[]] -> false; - [ConfiguredNS] -> ConfiguredNS =/= PayloadNS - end, - % pubsub#deliver_payloads true - % pubsub#persist_items true -> 1 item; false -> 0 item - if - not PublishFeature -> - %% Node does not support item publication - {error, extended_error('feature-not-implemented', unsupported, "publish")}; - PayloadSize > PayloadMaxSize -> - %% Entity attempts to publish very large payload - {error, extended_error('not-acceptable', "payload-too-big")}; - (PayloadCount == 0) and (Payload == []) -> - %% Publisher attempts to publish to payload node with no payload - {error, extended_error('bad-request', "payload-required")}; - (PayloadCount > 1) or (PayloadCount == 0) or InvalidNS -> - %% Entity attempts to publish item with multiple payload elements - %% or with wrong payload NS - {error, extended_error('bad-request', "invalid-payload")}; - (DeliverPayloads == 0) and (PersistItems == 0) and (PayloadSize > 0) -> - %% Publisher attempts to publish to transient notification node with item - {error, extended_error('bad-request', "item-forbidden")}; - ((DeliverPayloads == 1) or (PersistItems == 1)) and (PayloadSize == 0) -> - %% Publisher attempts to publish to persistent node with no item - {error, extended_error('bad-request', "item-required")}; - true -> - node_call(Type, publish_item, [Nidx, Publisher, PublishModel, MaxItems, ItemId, Payload]) - end - end, + Features = features(Type), + PublishFeature = lists:member("publish", Features), + PublishModel = get_option(Options, publish_model), + MaxItems = max_items(Host, Options), + DeliverPayloads = get_option(Options, deliver_payloads), + PersistItems = get_option(Options, persist_items), + {PayloadCount, PayloadNS} = payload_els_ns(Payload), + PayloadSize = size(term_to_binary(Payload)), + PayloadMaxSize = get_option(Options, max_payload_size), + InvalidNS = case get_option(Options, type) of + false -> false; + [[]] -> false; + [ConfiguredNS] -> ConfiguredNS =/= PayloadNS + end, + % pubsub#deliver_payloads true + % pubsub#persist_items true -> 1 item; false -> 0 item + if + not PublishFeature -> + %% Node does not support item publication + {error, extended_error('feature-not-implemented', unsupported, "publish")}; + PayloadSize > PayloadMaxSize -> + %% Entity attempts to publish very large payload + {error, extended_error('not-acceptable', "payload-too-big")}; + (PayloadCount == 0) and (Payload == []) -> + %% Publisher attempts to publish to payload node with no payload + {error, extended_error('bad-request', "payload-required")}; + (PayloadCount > 1) or (PayloadCount == 0) or InvalidNS -> + %% Entity attempts to publish item with multiple payload elements + %% or with wrong payload NS + {error, extended_error('bad-request', "invalid-payload")}; + (DeliverPayloads == 0) and (PersistItems == 0) and (PayloadSize > 0) -> + %% Publisher attempts to publish to transient notification node with item + {error, extended_error('bad-request', "item-forbidden")}; + ((DeliverPayloads == 1) or (PersistItems == 1)) and (PayloadSize == 0) -> + %% Publisher attempts to publish to persistent node with no item + {error, extended_error('bad-request', "item-required")}; + true -> + node_call(Type, publish_item, [Nidx, Publisher, PublishModel, MaxItems, ItemId, Payload]) + end + end, ServerHostB = list_to_binary(ServerHost), ejabberd_hooks:run(pubsub_publish_item, ServerHostB, [ServerHost, Node, Publisher, service_jid(Host), ItemId, Payload]), Reply = #xmlel{ns = ?NS_PUBSUB, name = 'pubsub', children = - [#xmlel{ns = ?NS_PUBSUB, name = 'publish', attrs = nodeAttr(Node), children = - [#xmlel{ns = ?NS_PUBSUB, name = 'item', attrs = itemAttr(ItemId)}]}]}, + [#xmlel{ns = ?NS_PUBSUB, name = 'publish', attrs = nodeAttr(Node), children = + [#xmlel{ns = ?NS_PUBSUB, name = 'item', attrs = itemAttr(ItemId)}]}]}, case transaction(Host, Node, Action, sync_dirty) of {result, {TNode, {Result, Broadcast, Removed}}} -> Nidx = TNode#pubsub_node.idx, Type = TNode#pubsub_node.type, Options = TNode#pubsub_node.options, BroadcastPayload = case Broadcast of - default -> Payload; - broadcast -> Payload; - PluginPayload -> PluginPayload - end, + default -> Payload; + broadcast -> Payload; + PluginPayload -> PluginPayload + end, broadcast_publish_item(Host, Node, Nidx, Type, Options, Removed, ItemId, jlib:short_prepd_jid(Publisher), BroadcastPayload), set_cached_item(Host, Nidx, ItemId, Publisher, Payload), case Result of @@ -2193,23 +2529,23 @@ delete_item(_, "", _, _, _) -> {error, extended_error('bad-request', "node-required")}; delete_item(Host, Node, Publisher, ItemId, ForceNotify) -> Action = fun(#pubsub_node{options = Options, type = Type, idx = Nidx}) -> - Features = features(Type), - PersistentFeature = lists:member("persistent-items", Features), - DeleteFeature = lists:member("delete-items", Features), - PublishModel = get_option(Options, publish_model), - if - %%-> iq_pubsub just does that matchs - %% %% Request does not specify an item - %% {error, extended_error('bad-request', "item-required")}; - not PersistentFeature -> - %% Node does not support persistent items - {error, extended_error('feature-not-implemented', unsupported, "persistent-items")}; - not DeleteFeature -> - %% Service does not support item deletion - {error, extended_error('feature-not-implemented', unsupported, "delete-items")}; - true -> - node_call(Type, delete_item, [Nidx, Publisher, PublishModel, ItemId]) - end + Features = features(Type), + PersistentFeature = lists:member("persistent-items", Features), + DeleteFeature = lists:member("delete-items", Features), + PublishModel = get_option(Options, publish_model), + if + %%-> iq_pubsub just does that matchs + %% %% Request does not specify an item + %% {error, extended_error('bad-request', "item-required")}; + not PersistentFeature -> + %% Node does not support persistent items + {error, extended_error('feature-not-implemented', unsupported, "persistent-items")}; + not DeleteFeature -> + %% Service does not support item deletion + {error, extended_error('feature-not-implemented', unsupported, "delete-items")}; + true -> + node_call(Type, delete_item, [Nidx, Publisher, PublishModel, ItemId]) + end end, Reply = [], case transaction(Host, Node, Action, sync_dirty) of @@ -2219,8 +2555,8 @@ delete_item(Host, Node, Publisher, ItemId, ForceNotify) -> Options = TNode#pubsub_node.options, broadcast_retract_items(Host, Node, Nidx, Type, Options, [ItemId], ForceNotify), case get_cached_item(Host, Nidx) of - #pubsub_item{id = {ItemId, Nidx}} -> unset_cached_item(Host, Nidx); - _ -> ok + #pubsub_item{id = {ItemId, Nidx}} -> unset_cached_item(Host, Nidx); + _ -> ok end, case Result of default -> {result, Reply}; @@ -2308,60 +2644,78 @@ get_items(Host, Node, From, SubId, SMaxItems, ItemIds) -> {error, Error}; _ -> Action = fun(#pubsub_node{options = Options, type = Type, idx = Nidx, owners = Owners}) -> - Features = features(Type), - RetreiveFeature = lists:member("retrieve-items", Features), - PersistentFeature = lists:member("persistent-items", Features), - AccessModel = get_option(Options, access_model), - AllowedGroups = get_option(Options, roster_groups_allowed, []), - {PresenceSubscription, RosterGroup} = get_presence_and_roster_permissions(Host, From, Owners, AccessModel, AllowedGroups), - if - not RetreiveFeature -> - %% Item Retrieval Not Supported - {error, extended_error('feature-not-implemented', unsupported, "retrieve-items")}; - not PersistentFeature -> - %% Persistent Items Not Supported - {error, extended_error('feature-not-implemented', unsupported, "persistent-items")}; - true -> - node_call(Type, get_items, - [Nidx, From, - AccessModel, PresenceSubscription, RosterGroup, - SubId]) - end - end, - case transaction(Host, Node, Action, sync_dirty) of + Features = features(Type), + RetreiveFeature = lists:member("retrieve-items", Features), + PersistentFeature = lists:member("persistent-items", Features), + AccessModel = get_option(Options, access_model), + AllowedGroups = get_option(Options, roster_groups_allowed, []), + {PresenceSubscription, RosterGroup} = get_presence_and_roster_permissions(Host, From, Owners, AccessModel, AllowedGroups), + if + not RetreiveFeature -> + %% Item Retrieval Not Supported + {error, extended_error('feature-not-implemented', unsupported, "retrieve-items")}; + not PersistentFeature -> + %% Persistent Items Not Supported + {error, extended_error('feature-not-implemented', unsupported, "persistent-items")}; + true -> + node_call(Type, get_items, + [Nidx, From, + AccessModel, PresenceSubscription, RosterGroup, + SubId]) + end + end, + case transaction(Host, Node, Action, sync_dirty) of {result, {_, Items}} -> SendItems = case ItemIds of - [] -> - Items; - _ -> - lists:filter(fun(#pubsub_item{id = {ItemId, _}}) -> - lists:member(ItemId, ItemIds) - end, Items) - end, + [] -> + Items; + _ -> + lists:filter(fun(#pubsub_item{id = {ItemId, _}}) -> + lists:member(ItemId, ItemIds) + end, Items) + end, %% Generate the XML response (Item list), limiting the %% number of items sent to MaxItems: {result, #xmlel{ns = ?NS_PUBSUB, name = 'pubsub', children = - [#xmlel{ns = ?NS_PUBSUB, name = 'items', attrs = nodeAttr(Node), children = - itemsEls(lists:sublist(SendItems, MaxItems))}]}}; + [#xmlel{ns = ?NS_PUBSUB, name = 'items', attrs = nodeAttr(Node), children = + itemsEls(lists:sublist(SendItems, MaxItems))}]}}; Error -> Error end end. -get_items(Host, Node) -> - Action = fun(#pubsub_node{type = Type, idx = Nidx}) -> - node_call(Type, get_items, [Nidx, service_jid(Host)]) - end, - case transaction(Host, Node, Action, sync_dirty) of - {result, {_, Items}} -> Items; - Error -> Error + +%% TODO : fix +-spec(get_items/2 :: + ( + Host :: host(), + NodeId :: nodeId()) + -> Items :: [] | [Item::pubsubItem()] + ). + +get_items(Host, NodeId) -> + Action = fun(#pubsub_node{type = Type, idx = NodeIdx}) -> + node_call(Type, get_items, [NodeIdx, service_jid(Host)]) + end, + case transaction(Host, NodeId, Action, sync_dirty) of + {result, {_, Items}} -> Items + %Error -> Error end. -get_item(Host, Node, ItemId) -> - Action = fun(#pubsub_node{type = Type, idx = Nidx}) -> - node_call(Type, get_item, [Nidx, ItemId]) - end, - case transaction(Host, Node, Action, sync_dirty) of +%% TODO : fix +-spec(get_item/3 :: + ( + Host :: host(), + NodeId :: nodeId(), + ItemId :: itemId()) + -> {'result', Item::pubsubItem()} | {'error', 'item-not-found'} + ). + +get_item(Host, NodeId, ItemId) -> + Action = fun(#pubsub_node{type = Type, idx = NodeIdx}) -> + node_call(Type, get_item, [NodeIdx, ItemId]) + end, + case transaction(Host, NodeId, Action, sync_dirty) of {result, {_, Items}} -> Items; Error -> Error end. @@ -2375,40 +2729,40 @@ get_item(Host, Node, ItemId) -> %% Number = last | integer() %% @doc

Resend the items of a node to the user.

%% @todo use cache-last-item feature -send_items(Host, Node, NodeId, Type, LJID, last) -> +send_items(Host, Node, NodeId, Type, LJID, 'last') -> case get_cached_item(Host, NodeId) of undefined -> send_items(Host, Node, NodeId, Type, LJID, 1); LastItem -> {ModifNow, ModifUSR} = LastItem#pubsub_item.modification, Stanza = event_stanza_with_delay( - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), - children = itemsEls([LastItem])}], ModifNow, ModifUSR), + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), + children = itemsEls([LastItem])}], ModifNow, ModifUSR), ejabberd_router:route(service_jid(Host), exmpp_jid:make(LJID), Stanza) end; send_items(Host, Node, NodeId, Type, {LU, LS, LR} = LJID, Number) -> ToSend = case node_action(Host, Type, get_items, [NodeId, LJID]) of - {result, []} -> - []; - {result, Items} -> - case Number of - N when N > 0 -> lists:sublist(Items, N); - _ -> Items - end; - _ -> - [] - end, + {result, []} -> + []; + {result, Items} -> + case Number of + N when N > 0 -> lists:sublist(Items, N); + _ -> Items + end; + _ -> + [] + end, Stanza = case ToSend of - [LastItem] -> - {ModifNow, ModifUSR} = LastItem#pubsub_item.modification, - event_stanza_with_delay( - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = - itemsEls(ToSend)}], ModifNow, ModifUSR); - _ -> - event_stanza( - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = - itemsEls(ToSend)}]) - end, + [LastItem] -> + {ModifNow, ModifUSR} = LastItem#pubsub_item.modification, + event_stanza_with_delay( + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = + itemsEls(ToSend)}], ModifNow, ModifUSR); + _ -> + event_stanza( + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = + itemsEls(ToSend)}]) + end, ejabberd_router:route(service_jid(Host), exmpp_jid:make(LU, LS, LR), Stanza). %% @spec (Host, JID, Plugins) -> {error, Reason} | {result, Response} @@ -2438,43 +2792,43 @@ get_affiliations(Host, JID, Plugins) when is_list(Plugins) -> fun({_, none}) -> []; ({#pubsub_node{id = {_, Node}}, Affiliation}) -> [#xmlel{ns = ?NS_PUBSUB, name = 'affiliation', attrs = - [?XMLATTR('node', node_to_string(Node)), - ?XMLATTR('affiliation', affiliation_to_string(Affiliation))]}] + [?XMLATTR('node', node_to_string(Node)), + ?XMLATTR('affiliation', affiliation_to_string(Affiliation))]}] end, lists:usort(lists:flatten(Affiliations))), {result, #xmlel{ns = ?NS_PUBSUB, name = 'pubsub', children = - [#xmlel{ns = ?NS_PUBSUB, name = 'affiliations', children = - Entities}]}}; + [#xmlel{ns = ?NS_PUBSUB, name = 'affiliations', children = + Entities}]}}; {Error, _} -> Error end; get_affiliations(Host, Node, JID) -> Action = fun(#pubsub_node{type = Type, idx = Nidx}) -> - Features = features(Type), - RetrieveFeature = lists:member("modify-affiliations", Features), - {result, Affiliation} = node_call(Type, get_affiliation, [Nidx, JID]), - if - not RetrieveFeature -> - %% Service does not support modify affiliations - {error, extended_error('feature-not-implemented', unsupported, "modify-affiliations")}; - Affiliation /= owner -> - %% Entity is not an owner - {error, 'forbidden'}; - true -> - node_call(Type, get_node_affiliations, [Nidx]) - end - end, + Features = features(Type), + RetrieveFeature = lists:member("modify-affiliations", Features), + {result, Affiliation} = node_call(Type, get_affiliation, [Nidx, JID]), + if + not RetrieveFeature -> + %% Service does not support modify affiliations + {error, extended_error('feature-not-implemented', unsupported, "modify-affiliations")}; + Affiliation /= owner -> + %% Entity is not an owner + {error, 'forbidden'}; + true -> + node_call(Type, get_node_affiliations, [Nidx]) + end + end, case transaction(Host, Node, Action, sync_dirty) of {result, {_, Affiliations}} -> Entities = lists:flatmap( fun({_, none}) -> []; ({{AU, AS, AR}, Affiliation}) -> [#xmlel{ns = ?NS_PUBSUB_OWNER, name = 'affiliation', attrs = - [?XMLATTR('jid', exmpp_jid:to_binary(AU, AS, AR)), - ?XMLATTR('affiliation', affiliation_to_string(Affiliation))]}] + [?XMLATTR('jid', exmpp_jid:to_binary(AU, AS, AR)), + ?XMLATTR('affiliation', affiliation_to_string(Affiliation))]}] end, Affiliations), {result, #xmlel{ns = ?NS_PUBSUB_OWNER, name = 'pubsub', children = - [#xmlel{ns = ?NS_PUBSUB_OWNER, name = 'affiliations', attrs = nodeAttr(Node), children = - Entities}]}}; + [#xmlel{ns = ?NS_PUBSUB_OWNER, name = 'affiliations', attrs = nodeAttr(Node), children = + Entities}]}}; Error -> Error end. @@ -2491,11 +2845,11 @@ set_affiliations(Host, Node, From, EntitiesEls) -> case El of #xmlel{name = 'affiliation', attrs = Attrs} -> JID = try - exmpp_jid:parse( - exmpp_xml:get_attribute_from_list(Attrs, 'jid', "")) - catch - _:_ -> error - end, + exmpp_jid:parse( + exmpp_xml:get_attribute_from_list(Attrs, 'jid', "")) + catch + _:_ -> error + end, Affiliation = string_to_affiliation( exmpp_xml:get_attribute_from_list_as_list(Attrs, 'affiliation', "")), if @@ -2513,38 +2867,38 @@ set_affiliations(Host, Node, From, EntitiesEls) -> {error, 'bad-request'}; _ -> Action = fun(#pubsub_node{owners = Owners, type = Type, idx = Nidx}=N) -> - case lists:member(Owner, Owners) of - true -> - OwnerJID = exmpp_jid:make(Owner), - FilteredEntities = case Owners of - [Owner] -> [E || E <- Entities, element(1, E) =/= OwnerJID]; - _ -> Entities - end, - lists:foreach( - fun({JID, Affiliation}) -> - {result, _} = node_call(Type, set_affiliation, [Nidx, JID, Affiliation]), - case Affiliation of - owner -> - NewOwner = jlib:short_prepd_bare_jid(JID), - NewOwners = [NewOwner|Owners], - tree_call(Host, set_node, [N#pubsub_node{owners = NewOwners}]); - none -> - OldOwner = jlib:short_prepd_bare_jid(JID), - case lists:member(OldOwner, Owners) of - true -> - NewOwners = Owners--[OldOwner], - tree_call(Host, set_node, [N#pubsub_node{owners = NewOwners}]); - _ -> - ok - end; - _ -> - ok - end - end, FilteredEntities), - {result, []}; - _ -> - {error, 'forbidden'} - end + case lists:member(Owner, Owners) of + true -> + OwnerJID = exmpp_jid:make(Owner), + FilteredEntities = case Owners of + [Owner] -> [E || E <- Entities, element(1, E) =/= OwnerJID]; + _ -> Entities + end, + lists:foreach( + fun({JID, Affiliation}) -> + {result, _} = node_call(Type, set_affiliation, [Nidx, JID, Affiliation]), + case Affiliation of + owner -> + NewOwner = jlib:short_prepd_bare_jid(JID), + NewOwners = [NewOwner|Owners], + tree_call(Host, set_node, [N#pubsub_node{owners = NewOwners}]); + none -> + OldOwner = jlib:short_prepd_bare_jid(JID), + case lists:member(OldOwner, Owners) of + true -> + NewOwners = Owners--[OldOwner], + tree_call(Host, set_node, [N#pubsub_node{owners = NewOwners}]); + _ -> + ok + end; + _ -> + ok + end + end, FilteredEntities), + {result, []}; + _ -> + {error, 'forbidden'} + end end, case transaction(Host, Node, Action, sync_dirty) of {result, {_, Result}} -> {result, Result}; @@ -2558,9 +2912,9 @@ get_options(Host, Node, JID, SubId, Lang) -> true -> get_options_helper(JID, Lang, Node, Nidx, SubId, Type); false -> - {error, extended_error( - 'feature-not-implemented', - unsupported, "subscription-options")} + {error, extended_error( + 'feature-not-implemented', + unsupported, "subscription-options")} end end, case transaction(Host, Node, Action, sync_dirty) of @@ -2570,16 +2924,16 @@ get_options(Host, Node, JID, SubId, Lang) -> get_options_helper(JID, Lang, Node, NodeId, SubId, Type) -> Subscriber = try exmpp_jid:parse(JID) of - J -> jlib:short_jid(J) - catch - _ -> + J -> jlib:short_jid(J) + catch + _ -> exmpp_jid:make("", "", "") %% TODO, check if use <<>> instead of "" end, {result, Subs} = node_call(Type, get_subscriptions, [NodeId, Subscriber]), SubIds = lists:foldl(fun({subscribed, SID}, Acc) -> [SID | Acc]; - (_, Acc) -> + (_, Acc) -> Acc end, [], Subs), case {SubId, SubIds} of @@ -2601,7 +2955,7 @@ read_sub(Subscriber, Node, NodeId, SubId, Lang) -> {result, XdataEl} = pubsub_subscription:get_options_xform(Lang, Options), OptionsEl = #xmlel{ns = ?NS_PUBSUB, name = 'options', attrs = [ ?XMLATTR('jid', exmpp_jid:to_binary(Subscriber)), - ?XMLATTR('subid', SubId) | nodeAttr(Node)], + ?XMLATTR('subid', SubId) | nodeAttr(Node)], children = [XdataEl]}, PubsubEl = #xmlel{ns = ?NS_PUBSUB, name = 'pubsub', children = [OptionsEl]}, {result, PubsubEl} @@ -2614,9 +2968,9 @@ set_options(Host, Node, JID, SubId, Configuration) -> set_options_helper(Configuration, JID, Nidx, SubId, Type); false -> - {error, extended_error( - 'feature-not-implemented', - unsupported, "subscription-options")} + {error, extended_error( + 'feature-not-implemented', + unsupported, "subscription-options")} end end, case transaction(Host, Node, Action, sync_dirty) of @@ -2626,19 +2980,19 @@ set_options(Host, Node, JID, SubId, Configuration) -> set_options_helper(Configuration, JID, NodeId, SubId, Type) -> SubOpts = case pubsub_subscription:parse_options_xform(Configuration) of - {result, GoodSubOpts} -> GoodSubOpts; - _ -> invalid - end, + {result, GoodSubOpts} -> GoodSubOpts; + _ -> invalid + end, Subscriber = try exmpp_jid:parse(JID) of J -> J - catch + catch _ -> exmpp_jid:make("", "", "") %% TODO, check if use <<>> instead of "" end, {result, Subs} = node_call(Type, get_subscriptions, [NodeId, Subscriber]), SubIds = lists:foldl(fun({subscribed, SID}, Acc) -> [SID | Acc]; - (_, Acc) -> + (_, Acc) -> Acc end, [], Subs), case {SubId, SubIds} of @@ -2689,94 +3043,94 @@ get_subscriptions(Host, Node, JID, Plugins) when is_list(Plugins) -> {ok, Subscriptions} -> Entities = lists:flatmap( fun({_, none}) -> - []; + []; ({#pubsub_node{id = {_, SubsNode}}, Subscription}) -> - case Node of - <<>> -> - [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', attrs = - [?XMLATTR('node', node_to_string(SubsNode)), - ?XMLATTR('subscription', subscription_to_string(Subscription))]}]; - SubsNode -> - [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', attrs = - [?XMLATTR('subscription', subscription_to_string(Subscription))]}]; - _ -> - [] - end; - ({_, none, _}) -> - []; - ({#pubsub_node{id = {_, SubsNode}}, Subscription, SubId, SubJID}) -> - case Node of - <<>> -> - [#xmlel{ns = ?NS_PUBSUB, name='subscription', - attrs = [?XMLATTR('jid', exmpp_jid:to_binary(SubJID)), - ?XMLATTR('subid', SubId), - ?XMLATTR('subscription', subscription_to_string(Subscription)) | nodeAttr(SubsNode)]}]; - SubsNode -> - [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', - attrs = [?XMLATTR('jid', exmpp_jid:to_binary(SubJID)), - ?XMLATTR('subid', SubId), + case Node of + <<>> -> + [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', attrs = + [?XMLATTR('node', node_to_string(SubsNode)), ?XMLATTR('subscription', subscription_to_string(Subscription))]}]; - _ -> - [] - end; + SubsNode -> + [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', attrs = + [?XMLATTR('subscription', subscription_to_string(Subscription))]}]; + _ -> + [] + end; + ({_, none, _}) -> + []; + ({#pubsub_node{id = {_, SubsNode}}, Subscription, SubId, SubJID}) -> + case Node of + <<>> -> + [#xmlel{ns = ?NS_PUBSUB, name='subscription', + attrs = [?XMLATTR('jid', exmpp_jid:to_binary(SubJID)), + ?XMLATTR('subid', SubId), + ?XMLATTR('subscription', subscription_to_string(Subscription)) | nodeAttr(SubsNode)]}]; + SubsNode -> + [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', + attrs = [?XMLATTR('jid', exmpp_jid:to_binary(SubJID)), + ?XMLATTR('subid', SubId), + ?XMLATTR('subscription', subscription_to_string(Subscription))]}]; + _ -> + [] + end; ({#pubsub_node{id = {_, SubsNode}}, Subscription, SubJID}) -> - case Node of - <<>> -> - [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', attrs = - [?XMLATTR('node', node_to_string(SubsNode)), - ?XMLATTR('jid', exmpp_jid:to_binary(SubJID)), - ?XMLATTR('subscription', subscription_to_string(Subscription))]}]; - SubsNode -> - [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', attrs = - [?XMLATTR('jid', exmpp_jid:to_binary(SubJID)), - ?XMLATTR('subscription', subscription_to_string(Subscription))]}]; - _ -> - [] - end + case Node of + <<>> -> + [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', attrs = + [?XMLATTR('node', node_to_string(SubsNode)), + ?XMLATTR('jid', exmpp_jid:to_binary(SubJID)), + ?XMLATTR('subscription', subscription_to_string(Subscription))]}]; + SubsNode -> + [#xmlel{ns = ?NS_PUBSUB, name = 'subscription', attrs = + [?XMLATTR('jid', exmpp_jid:to_binary(SubJID)), + ?XMLATTR('subscription', subscription_to_string(Subscription))]}]; + _ -> + [] + end end, lists:usort(lists:flatten(Subscriptions))), {result, #xmlel{ns = ?NS_PUBSUB, name = 'pubsub', children = - [#xmlel{ns = ?NS_PUBSUB, name = 'subscriptions', children = - Entities}]}}; + [#xmlel{ns = ?NS_PUBSUB, name = 'subscriptions', children = + Entities}]}}; {Error, _} -> Error end. get_subscriptions(Host, Node, JID) -> Action = fun(#pubsub_node{type = Type, idx = Nidx}) -> - Features = features(Type), - RetrieveFeature = lists:member("manage-subscriptions", Features), - {result, Affiliation} = node_call(Type, get_affiliation, [Nidx, JID]), - if - not RetrieveFeature -> - %% Service does not support manage subscriptions - {error, extended_error('feature-not-implemented', unsupported, "manage-subscriptions")}; - Affiliation /= owner -> - %% Entity is not an owner - {error, 'forbidden'}; - true -> - node_call(Type, get_node_subscriptions, [Nidx]) - end - end, + Features = features(Type), + RetrieveFeature = lists:member("manage-subscriptions", Features), + {result, Affiliation} = node_call(Type, get_affiliation, [Nidx, JID]), + if + not RetrieveFeature -> + %% Service does not support manage subscriptions + {error, extended_error('feature-not-implemented', unsupported, "manage-subscriptions")}; + Affiliation /= owner -> + %% Entity is not an owner + {error, 'forbidden'}; + true -> + node_call(Type, get_node_subscriptions, [Nidx]) + end + end, case transaction(Host, Node, Action, sync_dirty) of -%% Fix bug when node owner retrieve an empty subscriptions list -% {result, {_, []}} -> -% {error, 'item-not-found'}; + %% Fix bug when node owner retrieve an empty subscriptions list + % {result, {_, []}} -> + % {error, 'item-not-found'}; {result, {_, Subscriptions}} -> Entities = lists:flatmap( fun({_, none}) -> []; ({_, pending, _}) -> []; ({{AU, AS, AR}, Subscription}) -> [#xmlel{ns = ?NS_PUBSUB_OWNER, name = 'subscription', attrs = - [?XMLATTR('jid', exmpp_jid:to_binary(AU, AS, AR)), - ?XMLATTR('subscription', subscription_to_string(Subscription))]}]; + [?XMLATTR('jid', exmpp_jid:to_binary(AU, AS, AR)), + ?XMLATTR('subscription', subscription_to_string(Subscription))]}]; ({{AU, AS, AR}, Subscription, SubId}) -> [#xmlel{ns = ?NS_PUBSUB_OWNER, name = 'subscription', attrs = - [?XMLATTR('jid', exmpp_jid:to_binary(AU, AS, AR)), - ?XMLATTR('subscription', subscription_to_string(Subscription)), - ?XMLATTR('subid', SubId)]}] + [?XMLATTR('jid', exmpp_jid:to_binary(AU, AS, AR)), + ?XMLATTR('subscription', subscription_to_string(Subscription)), + ?XMLATTR('subid', SubId)]}] end, Subscriptions), {result, #xmlel{ns = ?NS_PUBSUB_OWNER, name = 'pubsub', children = - [#xmlel{ns = ?NS_PUBSUB_OWNER, name = 'subscriptions', attrs = nodeAttr(Node), children = - Entities}]}}; + [#xmlel{ns = ?NS_PUBSUB_OWNER, name = 'subscriptions', attrs = nodeAttr(Node), children = + Entities}]}}; Error -> Error end. @@ -2793,12 +3147,12 @@ set_subscriptions(Host, Node, From, EntitiesEls) -> case El of #xmlel{name = 'subscription', attrs = Attrs} -> JID = try - exmpp_jid:parse( - exmpp_xml:get_attribute_from_list(Attrs, 'jid', "")) - catch - _:_ -> - error - end, + exmpp_jid:parse( + exmpp_xml:get_attribute_from_list(Attrs, 'jid', "")) + catch + _:_ -> + error + end, Subscription = string_to_subscription( exmpp_xml:get_attribute_from_list_as_list(Attrs, 'subscription', false)), SubId = exmpp_xml:get_attribute_from_list_as_list(Attrs, "subid", false), @@ -2817,36 +3171,36 @@ set_subscriptions(Host, Node, From, EntitiesEls) -> {error, 'bad-request'}; _ -> Notify = fun(JID, Sub, _SubId) -> - Stanza = #xmlel{ns = ?NS_JABBER_CLIENT, - name = 'message', - children = - [#xmlel{ns = ?NS_PUBSUB, - name = 'pubsub', - children = - [#xmlel{ns = ?NS_PUBSUB, - name = 'subscription', - attrs = [?XMLATTR('jid', exmpp_jid:to_binary(JID)), - ?XMLATTR('subsription', subscription_to_string(Sub)) | nodeAttr(Node)]}]}]}, - ejabberd_router:route(service_jid(Host), JID, Stanza) - end, + Stanza = #xmlel{ns = ?NS_JABBER_CLIENT, + name = 'message', + children = + [#xmlel{ns = ?NS_PUBSUB, + name = 'pubsub', + children = + [#xmlel{ns = ?NS_PUBSUB, + name = 'subscription', + attrs = [?XMLATTR('jid', exmpp_jid:to_binary(JID)), + ?XMLATTR('subsription', subscription_to_string(Sub)) | nodeAttr(Node)]}]}]}, + ejabberd_router:route(service_jid(Host), JID, Stanza) + end, Action = fun(#pubsub_node{owners = Owners, type = Type, idx = Nidx}) -> - case lists:member(Owner, Owners) of - true -> - Result = lists:foldl(fun({JID, Subscription, SubId}, Acc) -> + case lists:member(Owner, Owners) of + true -> + Result = lists:foldl(fun({JID, Subscription, SubId}, Acc) -> - case node_call(Type, set_subscriptions, [Nidx, JID, Subscription, SubId]) of - {error, Err} -> [{error, Err} | Acc]; - _ -> Notify(JID, Subscription, SubId), Acc - end - end, [], Entities), - case Result of - [] -> {result, []}; - _ -> {error, 'not-acceptable'} - end; - _ -> - {error, 'forbidden'} - end - end, + case node_call(Type, set_subscriptions, [Nidx, JID, Subscription, SubId]) of + {error, Err} -> [{error, Err} | Acc]; + _ -> Notify(JID, Subscription, SubId), Acc + end + end, [], Entities), + case Result of + [] -> {result, []}; + _ -> {error, 'not-acceptable'} + end; + _ -> + {error, 'forbidden'} + end + end, case transaction(Host, Node, Action, sync_dirty) of {result, {_, Result}} -> {result, Result}; Other -> Other @@ -2864,7 +3218,7 @@ get_roster_info(OwnerUser, OwnerServer, {SubscriberUser, SubscriberServer, _}, A {none, []}, [OwnerUser, OwnerServer, exmpp_jid:make({SubscriberUser, SubscriberServer, undefined})]), PresenceSubscription = (Subscription == both) orelse (Subscription == from) - orelse ({OwnerUser, OwnerServer} == {SubscriberUser, SubscriberServer}), + orelse ({OwnerUser, OwnerServer} == {SubscriberUser, SubscriberServer}), RosterGroup = lists:any(fun(Group) -> lists:member(Group, AllowedGroups) end, Groups), @@ -2922,10 +3276,16 @@ string_to_node(SNode) -> list_to_binary(SNode). %% @spec (Host) -> jid() %% Host = host() %% @doc

Generate pubsub service JID.

+-spec(service_jid/1 :: + ( + Host::host() | string()) + -> ServiceJID :: jidContact() | jidComponent() + ). + service_jid(Host) -> case Host of - {U,S,_} -> exmpp_jid:make(U, S); - _ -> exmpp_jid:make(Host) + {U,S,_} -> exmpp_jid:make(U, S); + _ -> exmpp_jid:make(Host) end. %% @spec (LJID, NotifyType, Depth, NodeOptions, SubOptions) -> boolean() @@ -2960,62 +3320,62 @@ node_to_deliver(LJID, NodeOptions) -> presence_can_deliver(_, false) -> true; presence_can_deliver({User, Server, Resource}, true) -> case mnesia:dirty_match_object({session, '_', '_', {User, Server}, '_', '_'}) of - [] -> false; - Sessions -> - lists:foldl(fun(_, true) -> true; - ({session, _, _, _, undefined, _}, _Acc) -> false; - ({session, _, {_, _, R}, _, _Priority, _}, _Acc) -> - case Resource of - undefined -> true; - R -> true; - _ -> false - end - end, false, Sessions) + [] -> false; + Sessions -> + lists:foldl(fun(_, true) -> true; + ({session, _, _, _, undefined, _}, _Acc) -> false; + ({session, _, {_, _, R}, _, _Priority, _}, _Acc) -> + case Resource of + undefined -> true; + R -> true; + _ -> false + end + end, false, Sessions) end. state_can_deliver({U, S, R}, []) -> [{U, S, R}]; state_can_deliver({U, S, R}, SubOptions) -> %% Check SubOptions for 'show_values' case lists:keysearch('show_values', 1, SubOptions) of - %% If not in suboptions, item can be delivered, case doesn't apply - false -> [{U, S, R}]; - %% If in a suboptions ... - {_, {_, ShowValues}} -> - %% Get subscriber resources - Resources = case R of - %% If the subscriber JID is a bare one, get all its resources - [] -> user_resources(U, S); - %% If the subscriber JID is a full one, use its resource - R -> [R] - end, - %% For each resource, test if the item is allowed to be delivered - %% based on resource state - lists:foldl( - fun(Resource, Acc) -> - get_resource_state({U, S, Resource}, ShowValues, Acc) - end, [], Resources) + %% If not in suboptions, item can be delivered, case doesn't apply + false -> [{U, S, R}]; + %% If in a suboptions ... + {_, {_, ShowValues}} -> + %% Get subscriber resources + Resources = case R of + %% If the subscriber JID is a bare one, get all its resources + [] -> user_resources(U, S); + %% If the subscriber JID is a full one, use its resource + R -> [R] + end, + %% For each resource, test if the item is allowed to be delivered + %% based on resource state + lists:foldl( + fun(Resource, Acc) -> + get_resource_state({U, S, Resource}, ShowValues, Acc) + end, [], Resources) end. get_resource_state({U, S, R}, ShowValues, JIDs) -> %% Get user session PID case ejabberd_sm:get_session_pid(exmpp_jid:make(U, S, R)) of - %% If no PID, item can be delivered - none -> lists:append([{U, S, R}], JIDs); - %% If PID ... - Pid -> - %% Get user resource state - %% TODO : add a catch clause - Show = case ejabberd_c2s:get_presence(Pid) of - {_, _, "available", _} -> "online"; - {_, _, State, _} -> State - end, - %% Is current resource state listed in 'show-values' suboption ? - case lists:member(Show, ShowValues) of %andalso Show =/= "online" of - %% If yes, item can be delivered - true -> lists:append([{U, S, R}], JIDs); - %% If no, item can't be delivered - false -> JIDs - end + %% If no PID, item can be delivered + none -> lists:append([{U, S, R}], JIDs); + %% If PID ... + Pid -> + %% Get user resource state + %% TODO : add a catch clause + Show = case ejabberd_c2s:get_presence(Pid) of + {_, _, "available", _} -> "online"; + {_, _, State, _} -> State + end, + %% Is current resource state listed in 'show-values' suboption ? + case lists:member(Show, ShowValues) of %andalso Show =/= "online" of + %% If yes, item can be delivered + true -> lists:append([{U, S, R}], JIDs); + %% If no, item can't be delivered + false -> JIDs + end end. %% @spec (Payload) -> int() @@ -3041,23 +3401,23 @@ event_stanza_with_delay(Els, ModifNow, {U, S, R}) -> event_stanza_withmoreels(Els, MoreEls) -> #xmlel{ns = ?NS_JABBER_CLIENT, name = 'message', children = - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'event', children = Els} | MoreEls]}. + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'event', children = Els} | MoreEls]}. %%%%%% broadcast functions broadcast_publish_item(Host, Node, NodeId, Type, Options, Removed, ItemId, From, Payload) -> - %broadcast(Host, Node, NodeId, Options, none, true, 'items', ItemEls) + %broadcast(Host, Node, NodeId, Options, none, true, 'items', ItemEls) case get_collection_subscriptions(Host, Node) of [] -> {result, false}; SubsByDepth when is_list(SubsByDepth) -> Content = case get_option(Options, deliver_payloads) of - true -> Payload; - false -> [] - end, + true -> Payload; + false -> [] + end, Stanza = event_stanza( - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'item', attrs = itemAttr(ItemId), children = Content}]}]), + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'item', attrs = itemAttr(ItemId), children = Content}]}]), broadcast_stanza(Host, From, Node, NodeId, Type, Options, SubsByDepth, items, Stanza, true), case Removed of [] -> @@ -3066,8 +3426,8 @@ broadcast_publish_item(Host, Node, NodeId, Type, Options, Removed, ItemId, From, case get_option(Options, notify_retract) of true -> RetractStanza = event_stanza( - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'retract', attrs = itemAttr(RId)} || RId <- Removed]}]), + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'retract', attrs = itemAttr(RId)} || RId <- Removed]}]), broadcast_stanza(Host, Node, NodeId, Type, Options, SubsByDepth, items, RetractStanza, true); _ -> ok @@ -3083,7 +3443,7 @@ broadcast_retract_items(Host, Node, NodeId, Type, NodeOptions, ItemIds) -> broadcast_retract_items(_Host, _Node, _NodeId, _Type, _NodeOptions, [], _ForceNotify) -> {result, false}; broadcast_retract_items(Host, Node, NodeId, Type, NodeOptions, ItemIds, ForceNotify) -> - %broadcast(Host, Node, NodeId, NodeOptions, notify_retract, ForceNotify, 'retract', RetractEls) + %broadcast(Host, Node, NodeId, NodeOptions, notify_retract, ForceNotify, 'retract', RetractEls) case (get_option(NodeOptions, notify_retract) or ForceNotify) of true -> case get_collection_subscriptions(Host, Node) of @@ -3091,8 +3451,8 @@ broadcast_retract_items(Host, Node, NodeId, Type, NodeOptions, ItemIds, ForceNot {result, false}; SubsByDepth when is_list(SubsByDepth)-> Stanza = event_stanza( - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'retract', attrs = itemAttr(ItemId)} || ItemId <- ItemIds]}]), + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'retract', attrs = itemAttr(ItemId)} || ItemId <- ItemIds]}]), broadcast_stanza(Host, Node, NodeId, Type, NodeOptions, SubsByDepth, items, Stanza, true), {result, true}; _ -> @@ -3103,7 +3463,7 @@ broadcast_retract_items(Host, Node, NodeId, Type, NodeOptions, ItemIds, ForceNot end. broadcast_purge_node(Host, Node, NodeId, Type, NodeOptions) -> - %broadcast(Host, Node, NodeId, NodeOptions, notify_retract, false, 'purge', []) + %broadcast(Host, Node, NodeId, NodeOptions, notify_retract, false, 'purge', []) case get_option(NodeOptions, notify_retract) of true -> case get_collection_subscriptions(Host, Node) of @@ -3111,7 +3471,7 @@ broadcast_purge_node(Host, Node, NodeId, Type, NodeOptions) -> {result, false}; SubsByDepth when is_list(SubsByDepth) -> Stanza = event_stanza( - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'purge', attrs = nodeAttr(Node)}]), + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'purge', attrs = nodeAttr(Node)}]), broadcast_stanza(Host, Node, NodeId, Type, NodeOptions, SubsByDepth, nodes, Stanza, false), {result, true}; _ -> @@ -3122,7 +3482,7 @@ broadcast_purge_node(Host, Node, NodeId, Type, NodeOptions) -> end. broadcast_removed_node(Host, Node, NodeId, Type, NodeOptions, SubsByDepth) -> - %broadcast(Host, Node, NodeId, NodeOptions, notify_delete, false, 'delete', []) + %broadcast(Host, Node, NodeId, NodeOptions, notify_delete, false, 'delete', []) case get_option(NodeOptions, notify_delete) of true -> case SubsByDepth of @@ -3130,7 +3490,7 @@ broadcast_removed_node(Host, Node, NodeId, Type, NodeOptions, SubsByDepth) -> {result, false}; _ -> Stanza = event_stanza( - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'delete', attrs = nodeAttr(Node)}]), + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'delete', attrs = nodeAttr(Node)}]), broadcast_stanza(Host, Node, NodeId, Type, NodeOptions, SubsByDepth, nodes, Stanza, false), {result, true} end; @@ -3146,7 +3506,7 @@ broadcast_created_node(Host, Node, NodeId, Type, NodeOptions, SubsByDepth) -> {result, true}. broadcast_config_notification(Host, Node, NodeId, Type, NodeOptions, Lang) -> - %broadcast(Host, Node, NodeId, NodeOptions, notify_config, false, 'items', ConfigEls) + %broadcast(Host, Node, NodeId, NodeOptions, notify_config, false, 'items', ConfigEls) case get_option(NodeOptions, notify_config) of true -> case get_collection_subscriptions(Host, Node) of @@ -3154,16 +3514,16 @@ broadcast_config_notification(Host, Node, NodeId, Type, NodeOptions, Lang) -> {result, false}; SubsByDepth when is_list(SubsByDepth) -> Content = case get_option(NodeOptions, deliver_payloads) of - true -> - [#xmlel{ns = ?NS_DATA_FORMS, name = 'x', attrs = [?XMLATTR('type', <<"form">>)], children = - get_configure_xfields(Type, NodeOptions, Lang, [])}]; - false -> - [] - end, + true -> + [#xmlel{ns = ?NS_DATA_FORMS, name = 'x', attrs = [?XMLATTR('type', <<"form">>)], children = + get_configure_xfields(Type, NodeOptions, Lang, [])}]; + false -> + [] + end, Stanza = event_stanza( - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = - [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'item', attrs = [?XMLATTR('id', <<"configuration">>)], children = - Content}]}]), + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'items', attrs = nodeAttr(Node), children = + [#xmlel{ns = ?NS_PUBSUB_EVENT, name = 'item', attrs = [?XMLATTR('id', <<"configuration">>)], children = + Content}]}]), broadcast_stanza(Host, Node, NodeId, Type, NodeOptions, SubsByDepth, nodes, Stanza, false), {result, true}; _ -> @@ -3173,102 +3533,126 @@ broadcast_config_notification(Host, Node, NodeId, Type, NodeOptions, Lang) -> {result, false} end. -get_collection_subscriptions(Host, Node) -> + +-spec(get_collection_subscriptions/2 :: + ( + Host :: host(), + NodeId :: nodeId()) + -> [] | [{Depth::integer(), Nodes :: [] | [Node::pubsubNode()]}] + ). + +get_collection_subscriptions(Host, NodeId) -> Action = fun() -> - {result, lists:map(fun({Depth, Nodes}) -> - {Depth, [{N, get_node_subs(N)} || N <- Nodes]} - end, tree_call(Host, get_parentnodes_tree, [Host, Node, service_jid(Host)]))} - end, + {result, lists:map(fun({Depth, Nodes}) -> + {Depth, [{Node, get_node_subs(Node)} || Node <- Nodes]} + end, tree_call(Host, get_parentnodes_tree, [Host, NodeId, service_jid(Host)]))} + end, case transaction(Action, sync_dirty) of {result, CollSubs} -> CollSubs; _ -> [] end. -get_node_subs(#pubsub_node{type = Type, idx = Nidx}) -> - case node_call(Type, get_node_subscriptions, [Nidx]) of - {result, Subs} -> get_options_for_subs(Nidx, Subs); + +-spec(get_node_subs/1 :: + ( + Node::pubsubNode()) + -> [] + | [{Entity::fullUsr(), SubId::subId(), Options::[nodeOption()] | []}] + | {'error', _} + ). + +get_node_subs(#pubsub_node{type = Type, idx = NodeIdx}) -> + case node_call(Type, get_node_subscriptions, [NodeIdx]) of + {result, Subs} -> get_options_for_subs(NodeIdx, Subs); Other -> Other end. -get_options_for_subs(Nidx, Subs) -> - lists:foldl(fun({JID, subscribed, SubId}, Acc) -> - case pubsub_subscription:read_subscription(JID, Nidx, SubId) of - {error, notfound} -> [{JID, SubId, []} | Acc]; - #pubsub_subscription{options = Options} -> [{JID, SubId, Options} | Acc]; - _ -> Acc + +-spec(get_options_for_subs/2 :: + ( + NodeIdx :: nodeIdx(), + Subs :: [] | [{Entity::fullUsr(), Subscription::subscription(), SubId::subId()}]) + -> [] | [{Entity::fullUsr(), SubId::subId(), Options::[nodeOption()] | []}] + ). + +get_options_for_subs(NodeIdx, Subs) -> + lists:foldl(fun({Entity, 'subscribed', SubId}, Acc) -> + case pubsub_subscription:read_subscription(Entity, NodeIdx, SubId) of + {error, 'notfound'} -> [{Entity, SubId, []} | Acc]; + #pubsub_subscription{options = Options} -> [{Entity, SubId, Options} | Acc] end; - (_, Acc) -> + (_, Acc) -> Acc end, [], Subs). -% TODO: merge broadcast code that way -%broadcast(Host, Node, NodeId, Type, NodeOptions, Feature, Force, ElName, SubEls) -> -% case (get_option(NodeOptions, Feature) or Force) of -% true -> -% case node_action(Host, Type, get_node_subscriptions, [NodeId]) of -% {result, []} -> -% {result, false}; -% {result, Subs} -> -% Stanza = event_stanza([{xmlelement, ElName, nodeAttr(Node), SubEls}]), -% broadcast_stanza(Host, Node, Type, NodeOptions, SubOpts, Stanza), -% {result, true}; -% _ -> -% {result, false} -% end; -% _ -> -% {result, false} -% end + % TODO: merge broadcast code that way + %broadcast(Host, Node, NodeId, Type, NodeOptions, Feature, Force, ElName, SubEls) -> + % case (get_option(NodeOptions, Feature) or Force) of + % true -> + % case node_action(Host, Type, get_node_subscriptions, [NodeId]) of + % {result, []} -> + % {result, false}; + % {result, Subs} -> + % Stanza = event_stanza([{xmlelement, ElName, nodeAttr(Node), SubEls}]), + % broadcast_stanza(Host, Node, Type, NodeOptions, SubOpts, Stanza), + % {result, true}; + % _ -> + % {result, false} + % end; + % _ -> + % {result, false} + % end broadcast_stanza(Host, _Node, _NodeId, _Type, NodeOptions, SubsByDepth, NotifyType, BaseStanza, SHIM) -> NotificationType = get_option(NodeOptions, notification_type, headline), BroadcastAll = get_option(NodeOptions, broadcast_all_resources), %% XXX this is not standard, but usefull From = service_jid(Host), Stanza = case NotificationType of - normal -> BaseStanza; - MsgType -> add_message_type(BaseStanza, atom_to_list(MsgType)) - end, + normal -> BaseStanza; + MsgType -> add_message_type(BaseStanza, atom_to_list(MsgType)) + end, %% Handles explicit subscriptions SubIdsByJID = subscribed_nodes_by_jid(NotifyType, SubsByDepth), lists:foreach(fun ({LJID, NodeName, SubIds}) -> - LJIDs = case BroadcastAll of - true -> - {U, S, _} = LJID, - [{U, S, R} || R <- user_resources(U, S)]; - false -> - [LJID] - end, - %% Determine if the stanza should have SHIM ('SubId' and 'name') headers - StanzaToSend = case {SHIM, SubIds} of - {false, _} -> - Stanza; - {true, [_]} -> - add_shim_headers(Stanza, collection_shim(NodeName)); - {true, SubIds} -> - add_shim_headers(Stanza, lists:append(collection_shim(NodeName), subid_shim(SubIds))) - end, - lists:foreach(fun(To) -> - ejabberd_router:route(From, exmpp_jid:make(To), StanzaToSend) - end, LJIDs) - end, SubIdsByJID). + LJIDs = case BroadcastAll of + true -> + {U, S, _} = LJID, + [{U, S, R} || R <- user_resources(U, S)]; + false -> + [LJID] + end, + %% Determine if the stanza should have SHIM ('SubId' and 'name') headers + StanzaToSend = case {SHIM, SubIds} of + {false, _} -> + Stanza; + {true, [_]} -> + add_shim_headers(Stanza, collection_shim(NodeName)); + {true, SubIds} -> + add_shim_headers(Stanza, lists:append(collection_shim(NodeName), subid_shim(SubIds))) + end, + lists:foreach(fun(To) -> + ejabberd_router:route(From, exmpp_jid:make(To), StanzaToSend) + end, LJIDs) + end, SubIdsByJID). broadcast_stanza({LUser, LServer, LResource}, Publisher, Node, NodeId, Type, NodeOptions, SubsByDepth, NotifyType, BaseStanza, SHIM) -> broadcast_stanza({LUser, LServer, LResource}, Node, NodeId, Type, NodeOptions, SubsByDepth, NotifyType, BaseStanza, SHIM), SenderResource = case LResource of - undefined -> - case user_resources(LUser, LServer) of - [Resource|_] -> Resource; - _ -> <<"">> - end; - _ -> - LResource - end, + undefined -> + case user_resources(LUser, LServer) of + [Resource|_] -> Resource; + _ -> <<"">> + end; + _ -> + LResource + end, %% Handles implicit presence subscriptions case ejabberd_sm:get_session_pid({LUser, LServer, SenderResource}) of C2SPid when is_pid(C2SPid) -> Stanza = case get_option(NodeOptions, notification_type, headline) of - normal -> BaseStanza; - MsgType -> add_message_type(BaseStanza, atom_to_list(MsgType)) - end, + normal -> BaseStanza; + MsgType -> add_message_type(BaseStanza, atom_to_list(MsgType)) + end, %% set the from address on the notification to the bare JID of the account owner %% Also, add "replyto" if entity has presence subscription to the account owner %% See XEP-0163 1.1 section 4.3.1 @@ -3278,17 +3662,17 @@ broadcast_stanza({LUser, LServer, LResource}, Publisher, Node, NodeId, Type, Nod case catch ejabberd_c2s:get_subscribed(C2SPid) of Contacts when is_list(Contacts) -> lists:foreach(fun({U, S, _}) -> - spawn(fun() -> - case ?IS_MY_HOST(S) of - true -> - lists:foreach(fun(R) -> - ejabberd_router:route(Sender, exmpp_jid:make(U, S, R), StanzaToSend) - end, user_resources(U, S)); - false -> - ejabberd_router:route(Sender, exmpp_jid:make(U, S), StanzaToSend) - end - end) - end, Contacts); + spawn(fun() -> + case ?IS_MY_HOST(S) of + true -> + lists:foreach(fun(R) -> + ejabberd_router:route(Sender, exmpp_jid:make(U, S, R), StanzaToSend) + end, user_resources(U, S)); + false -> + ejabberd_router:route(Sender, exmpp_jid:make(U, S), StanzaToSend) + end + end) + end, Contacts); _ -> ok end; @@ -3300,54 +3684,54 @@ broadcast_stanza(Host, _Publisher, Node, NodeId, Type, NodeOptions, SubsByDepth, subscribed_nodes_by_jid(NotifyType, SubsByDepth) -> NodesToDeliver = fun(Depth, Node, Subs, Acc) -> - NodeName = case Node#pubsub_node.id of - {_, N} -> N; - Other -> Other - end, - NodeOptions = Node#pubsub_node.options, - lists:foldl(fun({LJID, SubId, SubOptions}, {JIDs, Recipients}) -> - case is_to_deliver(LJID, NotifyType, Depth, NodeOptions, SubOptions) of - true -> - %% If is to deliver : - case state_can_deliver(LJID, SubOptions) of - [] -> {JIDs, Recipients}; - JIDsToDeliver -> - lists:foldl( - fun(JIDToDeliver, {JIDsAcc, RecipientsAcc}) -> - case lists:member(JIDToDeliver, JIDs) of - %% check if the JIDs co-accumulator contains the Subscription JID, - false -> - %% - if not, - %% - add the JID to JIDs list co-accumulator ; - %% - create a tuple of the JID, NodeId, and SubId (as list), - %% and add the tuple to the Recipients list co-accumulator - {[JIDToDeliver | JIDsAcc], [{JIDToDeliver, NodeName, [SubId]} | RecipientsAcc]}; - true -> - %% - if the JIDs co-accumulator contains the JID - %% get the tuple containing the JID from the Recipient list co-accumulator - {_, {JIDToDeliver, NodeName1, SubIds}} = lists:keysearch(JIDToDeliver, 1, RecipientsAcc), - %% delete the tuple from the Recipients list - % v1 : Recipients1 = lists:keydelete(LJID, 1, Recipients), - % v2 : Recipients1 = lists:keyreplace(LJID, 1, Recipients, {LJID, NodeId1, [SubId | SubIds]}), - %% add the SubId to the SubIds list in the tuple, - %% and add the tuple back to the Recipients list co-accumulator - % v1.1 : {JIDs, lists:append(Recipients1, [{LJID, NodeId1, lists:append(SubIds, [SubId])}])} - % v1.2 : {JIDs, [{LJID, NodeId1, [SubId | SubIds]} | Recipients1]} - % v2: {JIDs, Recipients1} - {JIDsAcc, lists:keyreplace(JIDToDeliver, 1, RecipientsAcc, {JIDToDeliver, NodeName1, [SubId | SubIds]})} - end - end, {JIDs, Recipients}, JIDsToDeliver) - end; - false -> - {JIDs, Recipients} - end - end, Acc, Subs) - end, + NodeName = case Node#pubsub_node.id of + {_, N} -> N; + Other -> Other + end, + NodeOptions = Node#pubsub_node.options, + lists:foldl(fun({LJID, SubId, SubOptions}, {JIDs, Recipients}) -> + case is_to_deliver(LJID, NotifyType, Depth, NodeOptions, SubOptions) of + true -> + %% If is to deliver : + case state_can_deliver(LJID, SubOptions) of + [] -> {JIDs, Recipients}; + JIDsToDeliver -> + lists:foldl( + fun(JIDToDeliver, {JIDsAcc, RecipientsAcc}) -> + case lists:member(JIDToDeliver, JIDs) of + %% check if the JIDs co-accumulator contains the Subscription JID, + false -> + %% - if not, + %% - add the JID to JIDs list co-accumulator ; + %% - create a tuple of the JID, NodeId, and SubId (as list), + %% and add the tuple to the Recipients list co-accumulator + {[JIDToDeliver | JIDsAcc], [{JIDToDeliver, NodeName, [SubId]} | RecipientsAcc]}; + true -> + %% - if the JIDs co-accumulator contains the JID + %% get the tuple containing the JID from the Recipient list co-accumulator + {_, {JIDToDeliver, NodeName1, SubIds}} = lists:keysearch(JIDToDeliver, 1, RecipientsAcc), + %% delete the tuple from the Recipients list + % v1 : Recipients1 = lists:keydelete(LJID, 1, Recipients), + % v2 : Recipients1 = lists:keyreplace(LJID, 1, Recipients, {LJID, NodeId1, [SubId | SubIds]}), + %% add the SubId to the SubIds list in the tuple, + %% and add the tuple back to the Recipients list co-accumulator + % v1.1 : {JIDs, lists:append(Recipients1, [{LJID, NodeId1, lists:append(SubIds, [SubId])}])} + % v1.2 : {JIDs, [{LJID, NodeId1, [SubId | SubIds]} | Recipients1]} + % v2: {JIDs, Recipients1} + {JIDsAcc, lists:keyreplace(JIDToDeliver, 1, RecipientsAcc, {JIDToDeliver, NodeName1, [SubId | SubIds]})} + end + end, {JIDs, Recipients}, JIDsToDeliver) + end; + false -> + {JIDs, Recipients} + end + end, Acc, Subs) + end, DepthsToDeliver = fun({Depth, SubsByNode}, Acc1) -> - lists:foldl(fun({Node, Subs}, Acc2) -> - NodesToDeliver(Depth, Node, Subs, Acc2) - end, Acc1, SubsByNode) - end, + lists:foldl(fun({Node, Subs}, Acc2) -> + NodesToDeliver(Depth, Node, Subs, Acc2) + end, Acc1, SubsByNode) + end, {_, JIDSubs} = lists:foldl(DepthsToDeliver, {[], []}, SubsByDepth), JIDSubs. @@ -3370,12 +3754,12 @@ get_configure(Host, ServerHost, Node, From, Lang) -> Groups = ejabberd_hooks:run_fold(roster_groups, ServerHostB, [], [ServerHostB]), {result, #xmlel{ns = ?NS_PUBSUB_OWNER, name = 'pubsub', children = - [#xmlel{ns = ?NS_PUBSUB_OWNER, name = 'configure', attrs = - nodeAttr(Node), children = - [#xmlel{ns = ?NS_DATA_FORMS, name = 'x', attrs = - [?XMLATTR('type', <<"form">>)], children = - get_configure_xfields(Type, Options, Lang, Groups) - }]}]}}; + [#xmlel{ns = ?NS_PUBSUB_OWNER, name = 'configure', attrs = + nodeAttr(Node), children = + [#xmlel{ns = ?NS_DATA_FORMS, name = 'x', attrs = + [?XMLATTR('type', <<"form">>)], children = + get_configure_xfields(Type, Options, Lang, Groups) + }]}]}}; _ -> {error, 'forbidden'} end @@ -3389,23 +3773,46 @@ get_default(Host, Node, _From, Lang) -> Type = select_type(Host, Host, Node), Options = node_options(Type), {result, #xmlel{ns = ?NS_PUBSUB_OWNER, name = 'pubsub', children = - [#xmlel{ns = ?NS_PUBSUB_OWNER, name = 'default', children = - [#xmlel{ns = ?NS_DATA_FORMS, name = 'x', attrs = [?XMLATTR('type', <<"form">>)], children = - get_configure_xfields(Type, Options, Lang, []) - }]}]}}. + [#xmlel{ns = ?NS_PUBSUB_OWNER, name = 'default', children = + [#xmlel{ns = ?NS_DATA_FORMS, name = 'x', attrs = [?XMLATTR('type', <<"form">>)], children = + get_configure_xfields(Type, Options, Lang, []) + }]}]}}. %% Get node option %% The result depend of the node type plugin system. +-spec(get_option/2 :: + ( + Options :: [] | [Option::nodeOption()], + Key :: atom()) + -> Value :: 'false' | term() + ). + get_option([], _) -> false; -get_option(Options, Var) -> - get_option(Options, Var, false). -get_option(Options, Var, Def) -> - case lists:keysearch(Var, 1, Options) of - {value, {_Val, Ret}} -> Ret; - _ -> Def +get_option(Options, Key) -> + get_option(Options, Key, false). + + +-spec(get_option/3 :: + ( + Options :: [] | [Option::nodeOption()], + Key :: atom(), + Default :: term()) + -> Value :: term() + ). + +get_option(Options, Key, Default) -> + case lists:keysearch(Key, 1, Options) of + {value, {_Key, Value}} -> Value; + _ -> Default end. %% Get default options from the module plugin. +-spec(node_options/1 :: + ( + Type::nodeType()) + -> Options::[Option::nodeOption()] + ). + node_options(Type) -> Module = list_to_atom(?PLUGIN_PREFIX ++ Type), case catch Module:options() of @@ -3427,22 +3834,29 @@ node_options(Type) -> %% @todo In practice, the current data structure means that we cannot manage %% millions of items on a given node. This should be addressed in a new %% version. +-spec(max_items/2 :: + ( + Host :: host(), + Options :: [Option::nodeOption()]) + -> MaxItems :: integer() | 'unlimited' + ). + max_items(Host, Options) -> - case get_option(Options, persist_items) of + case get_option(Options, 'persist_items') of true -> - case get_option(Options, max_items) of - false -> unlimited; + case get_option(Options, 'max_items') of + false -> 'unlimited'; Result when (Result < 0) -> 0; Result -> Result end; false -> - case get_option(Options, send_last_published_item) of - never -> + case get_option(Options, 'send_last_published_item') of + 'never' -> 0; _ -> case is_last_item_cache_enabled(Host) of - true -> 0; - false -> 1 + true -> 0; + false -> 1 end end end. @@ -3495,7 +3909,7 @@ get_configure_xfields(_Type, Options, Lang, Groups) -> ?LISTM_CONFIG_FIELD("Roster groups allowed to subscribe", roster_groups_allowed, Groups), ?ALIST_CONFIG_FIELD("Specify the publisher model", publish_model, [publishers, subscribers, open]), - ?BOOL_CONFIG_FIELD("Purge all items when the relevant publisher goes offline", purge_offline), + ?BOOL_CONFIG_FIELD("Purge all items when the relevant publisher goes offline", purge_offline), ?ALIST_CONFIG_FIELD("Specify the event message type", notification_type, [headline, normal]), ?INTEGER_CONFIG_FIELD("Max payload size in bytes", max_payload_size), @@ -3657,171 +4071,294 @@ set_xoption(Host, [{"pubsub#node", [Value]} | Opts], NewOpts) -> NewValue = string_to_node(Value), ?SET_LIST_XOPT(node, NewValue); set_xoption(Host, [_ | Opts], NewOpts) -> - % skip unknown field + % skip unknown field set_xoption(Host, Opts, NewOpts). + +-spec(get_max_items_node/1 :: + ( + Host :: host()) + -> MaxItems::integer() + ). + get_max_items_node({_, ServerHost, _}) -> get_max_items_node(ServerHost); get_max_items_node(Host) -> - case catch ets:lookup(gen_mod:get_module_proc(Host, config), max_items_node) of - [{max_items_node, Integer}] -> Integer; - _ -> ?MAXITEMS + case catch ets:lookup(gen_mod:get_module_proc(Host, 'config'), 'max_items_node') of + [{'max_items_node', Integer}] -> Integer; + _ -> ?MAXITEMS end. %%%% last item cache handling +-spec(is_last_item_cache_enabled/1 :: + ( + Host :: string() | host()) + -> IsLastItemCacheEnabled::boolean() + ). is_last_item_cache_enabled({_, ServerHost, _}) -> is_last_item_cache_enabled(binary_to_list(ServerHost)); is_last_item_cache_enabled(Host) -> - case catch ets:lookup(gen_mod:get_module_proc(Host, config), last_item_cache) of - [{last_item_cache, true}] -> true; - _ -> false + case catch ets:lookup(gen_mod:get_module_proc(Host, 'config'), 'last_item_cache') of + [{'last_item_cache', true}] -> true; + _ -> false end. + +-spec(set_cached_item/5 :: + ( + Host :: string() | host(), + NodeId :: nodeIdx(), + ItemId :: itemId(), + Publisher :: jidEntity(), + Payload :: payload()) + -> 'ok' | {'aborted', Reason::_} + ). + set_cached_item({_, ServerHost, _}, NodeId, ItemId, Publisher, Payload) -> set_cached_item(binary_to_list(ServerHost), NodeId, ItemId, Publisher, Payload); -set_cached_item(Host, NodeId, ItemId, Publisher, Payload) -> +set_cached_item(Host, NodeId, ItemId, #jid{node = U, domain = S} = _Publisher, Payload) -> case is_last_item_cache_enabled(Host) of - true -> mnesia:dirty_write({pubsub_last_item, NodeId, ItemId, {now(), jlib:short_prepd_bare_jid(Publisher)}, Payload}); - _ -> ok + true -> + mnesia:dirty_write({pubsub_last_item, NodeId, ItemId, {now(), {U,S,undefined}}, Payload}); + _ -> ok end. + + +-spec(unset_cached_item/2 :: + ( + Host :: string() | host(), + NodeId :: nodeIdx()) + -> 'ok' | {'aborted', Reason::_} + ). + unset_cached_item({_, ServerHost, _}, NodeId) -> unset_cached_item(binary_to_list(ServerHost), NodeId); unset_cached_item(Host, NodeId) -> case is_last_item_cache_enabled(Host) of - true -> mnesia:dirty_delete({pubsub_last_item, NodeId}); - _ -> ok + true -> mnesia:dirty_delete({pubsub_last_item, NodeId}); + _ -> ok end. + + +-spec(get_cached_item/2 :: + ( + Host :: string() | host(), + NodeId :: nodeIdx()) + -> CachedItem :: 'undefined' | pubsubItem() + ). + get_cached_item({_, ServerHost, _}, NodeId) -> get_cached_item(binary_to_list(ServerHost), NodeId); get_cached_item(Host, NodeId) -> case is_last_item_cache_enabled(Host) of - true -> - case mnesia:dirty_read({pubsub_last_item, NodeId}) of - [{pubsub_last_item, NodeId, ItemId, Creation, Payload}] -> - #pubsub_item{id = {ItemId, NodeId}, payload = Payload, - creation = Creation, modification = Creation}; + true -> + case mnesia:dirty_read({pubsub_last_item, NodeId}) of %% TODO + [{pubsub_last_item, NodeId, ItemId, Creation, Payload}] -> + #pubsub_item{id = {ItemId, NodeId}, payload = Payload, + creation = Creation, modification = Creation}; + _ -> + undefined + end; _ -> undefined - end; - _ -> - undefined end. %%%% plugin handling +-spec(host/1 :: + ( + ServerHost :: string() | binary()) + -> Host::string() + ). host(ServerHost) -> - case catch ets:lookup(gen_mod:get_module_proc(ServerHost, config), host) of - [{host, Host}] -> Host; - _ -> "pubsub."++ServerHost + case catch ets:lookup(gen_mod:get_module_proc(ServerHost, 'config'), 'host') of + [{'host', Host}] -> Host; + _ -> "pubsub."++ServerHost end. + + +-spec(plugins/1 :: + ( + Host :: binary() | string()) + -> Plugins::[Plugin::nodeType()] + ). + plugins(Host) when is_binary(Host) -> plugins(binary_to_list(Host)); plugins(Host) when is_list(Host) -> - case catch ets:lookup(gen_mod:get_module_proc(Host, config), plugins) of - [{plugins, []}] -> [?STDNODE]; - [{plugins, PL}] -> PL; - _ -> [?STDNODE] + case catch ets:lookup(gen_mod:get_module_proc(Host, 'config'), 'plugins') of + [{'plugins', []}] -> [?STDNODE]; + [{'plugins', Plugins}] -> Plugins; + _ -> [?STDNODE] end. -select_type(ServerHost, Host, Node, Type) when is_list(ServerHost) -> - select_type(list_to_binary(ServerHost), Host, Node, Type); -select_type(ServerHost, Host, Node, Type) -> + + +-spec(select_type/4 :: + ( + ServerHost :: binary() | string(), + Host :: host(), + NodeId :: nodeId(), + Type :: nodeType()) + -> SelectedType::nodeType() + ). + +select_type(ServerHost, Host, NodeId, Type) when is_binary(ServerHost) -> + select_type(binary_to_list(ServerHost), Host, NodeId, Type); +select_type(ServerHost, Host, NodeId, Type) -> SelectedType = case Host of - {_User, _Server, _Resource} -> - case catch ets:lookup(gen_mod:get_module_proc(ServerHost, config), pep_mapping) of - [{pep_mapping, PM}] -> proplists:get_value(node_to_string(Node), PM, ?PEPNODE); - _ -> ?PEPNODE - end; - _ -> - Type - end, - ConfiguredTypes = plugins(ServerHost), - case lists:member(SelectedType, ConfiguredTypes) of - true -> SelectedType; - false -> hd(ConfiguredTypes) + {_User, _Server, _Resource} -> + case catch ets:lookup(gen_mod:get_module_proc(ServerHost, 'config'), 'pep_mapping') of + [{'pep_mapping', PepMapping}] -> + proplists:get_value(node_to_string(NodeId), PepMapping, ?PEPNODE); + _ -> ?PEPNODE + end; + _ -> Type + end, + %ConfiguredTypes = plugins(ServerHost), + case lists:member(SelectedType, ConfiguredTypes = plugins(ServerHost)) of + true -> SelectedType; + false -> hd(ConfiguredTypes) end. -select_type(ServerHost, Host, Node) -> - select_type(ServerHost, Host, Node, hd(plugins(ServerHost))). + + +-spec(select_type/3 :: + ( + ServerHost :: binary() | string(), + Host :: host(), + NodeId :: nodeId()) + -> SelectedType::nodeType() + ). + +select_type(ServerHost, Host, NodeId) -> + select_type(ServerHost, Host, NodeId, hd(plugins(ServerHost))). + + +-spec(features/0 :: () -> Features::[Feature::string()]). features() -> - [ - % see plugin "access-authorize", % OPTIONAL - "access-open", % OPTIONAL this relates to access_model option in node_flat - "access-presence", % OPTIONAL this relates to access_model option in node_pep - %TODO "access-roster", % OPTIONAL - "access-whitelist", % OPTIONAL - % see plugin "auto-create", % OPTIONAL - % see plugin "auto-subscribe", % RECOMMENDED - "collections", % RECOMMENDED - "config-node", % RECOMMENDED - "create-and-configure", % RECOMMENDED - % see plugin "create-nodes", % RECOMMENDED - % see plugin "delete-items", % RECOMMENDED - % see plugin "delete-nodes", % RECOMMENDED - % see plugin "filtered-notifications", % RECOMMENDED - % see plugin "get-pending", % OPTIONAL - % see plugin "instant-nodes", % RECOMMENDED - "item-ids", % RECOMMENDED - "last-published", % RECOMMENDED - %TODO "cache-last-item", - %TODO "leased-subscription", % OPTIONAL - % see plugin "manage-subscriptions", % OPTIONAL - "member-affiliation", % RECOMMENDED - %TODO "meta-data", % RECOMMENDED - % see plugin "modify-affiliations", % OPTIONAL - % see plugin "multi-collection", % OPTIONAL - % see plugin "multi-subscribe", % OPTIONAL - % see plugin "outcast-affiliation", % RECOMMENDED - % see plugin "persistent-items", % RECOMMENDED - "presence-notifications", % OPTIONAL - "presence-subscribe", % RECOMMENDED - % see plugin "publish", % REQUIRED - %TODO "publish-options", % OPTIONAL - "publisher-affiliation", % RECOMMENDED - % see plugin "purge-nodes", % OPTIONAL - % see plugin "retract-items", % OPTIONAL - % see plugin "retrieve-affiliations", % RECOMMENDED - "retrieve-default" % RECOMMENDED - % see plugin "retrieve-items", % RECOMMENDED - % see plugin "retrieve-subscriptions", % RECOMMENDED - %TODO "shim", % OPTIONAL - % see plugin "subscribe", % REQUIRED - % see plugin "subscription-options", % OPTIONAL - % see plugin "subscription-notifications" % OPTIONAL - ]. + [ + % see plugin "access-authorize", % OPTIONAL + "access-open", % OPTIONAL this relates to access_model option in node_flat + "access-presence", % OPTIONAL this relates to access_model option in node_pep + %TODO "access-roster", % OPTIONAL + "access-whitelist", % OPTIONAL + % see plugin "auto-create", % OPTIONAL + % see plugin "auto-subscribe", % RECOMMENDED + "collections", % RECOMMENDED + "config-node", % RECOMMENDED + "create-and-configure", % RECOMMENDED + % see plugin "create-nodes", % RECOMMENDED + % see plugin "delete-items", % RECOMMENDED + % see plugin "delete-nodes", % RECOMMENDED + % see plugin "filtered-notifications", % RECOMMENDED + % see plugin "get-pending", % OPTIONAL + % see plugin "instant-nodes", % RECOMMENDED + "item-ids", % RECOMMENDED + "last-published", % RECOMMENDED + %TODO "cache-last-item", + %TODO "leased-subscription", % OPTIONAL + % see plugin "manage-subscriptions", % OPTIONAL + "member-affiliation", % RECOMMENDED + %TODO "meta-data", % RECOMMENDED + % see plugin "modify-affiliations", % OPTIONAL + % see plugin "multi-collection", % OPTIONAL + % see plugin "multi-subscribe", % OPTIONAL + % see plugin "outcast-affiliation", % RECOMMENDED + % see plugin "persistent-items", % RECOMMENDED + "presence-notifications", % OPTIONAL + "presence-subscribe", % RECOMMENDED + % see plugin "publish", % REQUIRED + %TODO "publish-options", % OPTIONAL + "publisher-affiliation", % RECOMMENDED + % see plugin "purge-nodes", % OPTIONAL + % see plugin "retract-items", % OPTIONAL + % see plugin "retrieve-affiliations", % RECOMMENDED + "retrieve-default" % RECOMMENDED + % see plugin "retrieve-items", % RECOMMENDED + % see plugin "retrieve-subscriptions", % RECOMMENDED + %TODO "shim", % OPTIONAL + % see plugin "subscribe", % REQUIRED + % see plugin "subscription-options", % OPTIONAL + % see plugin "subscription-notifications" % OPTIONAL + ]. + + +-spec(features/1 :: + ( + Type::nodeType()) + -> Features::[Feature::string()] + ). + features(Type) -> Module = list_to_atom(?PLUGIN_PREFIX++Type), features() ++ case catch Module:features() of {'EXIT', {undef, _}} -> []; Result -> Result end. -features(Host, <<>>) -> + + +-spec(features/2 :: + ( + Host :: string() | binary(), + NodeId :: nodeId()) + -> Features::[Feature::string()] + ). + +features(Host, <<>> = _NodeId) -> lists:usort(lists:foldl(fun(Plugin, Acc) -> - Acc ++ features(Plugin) - end, [], plugins(Host))); -features(Host, Node) -> + Acc ++ features(Plugin) + end, [], plugins(Host))); +features(Host, NodeId) -> Action = fun(#pubsub_node{type = Type}) -> {result, features(Type)} end, - case transaction(Host, Node, Action, sync_dirty) of - {result, Features} -> lists:usort(features() ++ Features); - _ -> features() + case transaction(Host, NodeId, Action, sync_dirty) of + {result, Features} -> lists:usort(features() ++ Features); + _ -> features() end. %% @doc

node tree plugin call.

+-spec(tree_call/3 :: + ( + Host :: string() | host(), + Function :: atom(), + Args :: [term()]) + -> any() %% TODO + ). + tree_call({_User, Server, _Resource}, Function, Args) -> tree_call(Server, Function, Args); tree_call(Host, Function, Args) -> ?DEBUG("tree_call ~p ~p ~p",[Host, Function, Args]), - Module = case catch ets:lookup(gen_mod:get_module_proc(Host, config), nodetree) of - [{nodetree, N}] -> N; - _ -> list_to_atom(?TREE_PREFIX ++ ?STDTREE) - end, + Module = case catch ets:lookup(gen_mod:get_module_proc(Host, 'config'), 'nodetree') of + [{'nodetree', NodeTree}] -> NodeTree; + _ -> list_to_atom(?TREE_PREFIX ++ ?STDTREE) + end, catch apply(Module, Function, Args). + + +-spec(tree_action/3 :: + ( + Host :: string() | host(), + Function :: atom(), + Args :: [term()]) + -> any() %% TODO + ). + tree_action(Host, Function, Args) -> ?DEBUG("tree_action ~p ~p ~p",[Host,Function,Args]), - Fun = fun() -> tree_call(Host, Function, Args) end, - catch mnesia:sync_dirty(Fun). + %Fun = fun() -> tree_call(Host, Function, Args) end, + catch mnesia:sync_dirty( + fun() -> tree_call(Host, Function, Args) end). %% @doc

node plugin call.

+-spec(node_call/3 :: + ( + Type :: nodeType(), + Function :: atom(), + Args :: [term()]) + -> {'result', Result::_} | {'error', Error::_} %% TODO + ). + node_call(Type, Function, Args) -> ?DEBUG("node_call ~p ~p ~p",[Type, Function, Args]), Module = list_to_atom(?PLUGIN_PREFIX++Type), @@ -3837,6 +4374,16 @@ node_call(Type, Function, Args) -> Result -> {result, Result} %% any other return value is forced as result end. + +-spec(node_action/4 :: + ( + Host :: string() | host(), + Type :: nodeType(), + Function :: atom(), + Args :: [term()]) + -> any() %% TODO + ). + node_action(Host, Type, Function, Args) -> ?DEBUG("node_action ~p ~p ~p ~p",[Host,Type,Function,Args]), transaction(fun() -> @@ -3844,13 +4391,22 @@ node_action(Host, Type, Function, Args) -> end, sync_dirty). %% @doc

plugin transaction handling.

-transaction(Host, Node, Action, Trans) -> +-spec(transaction/4 :: + ( + Host :: string() | host(), + NodeId :: nodeId(), + Action :: fun(), + Trans :: atom()) + -> {'result', {Node::pubsubNode(), Result::_}} | {'error', Error::_} + ). + +transaction(Host, NodeId, Action, Trans) -> transaction(fun() -> - case tree_call(Host, get_node, [Host, Node]) of - N when is_record(N, pubsub_node) -> - case Action(N) of - {result, Result} -> {result, {N, Result}}; - {atomic, {result, Result}} -> {result, {N, Result}}; + case tree_call(Host, get_node, [Host, NodeId]) of + #pubsub_node{} = Node -> + case Action(Node) of + {result, Result} -> {result, {Node, Result}}; + {atomic, {result, Result}} -> {result, {Node, Result}}; Other -> Other end; Error -> @@ -3858,11 +4414,28 @@ transaction(Host, Node, Action, Trans) -> end end, Trans). + +-spec(transaction/3 :: + ( + Host :: string() | host(), + Action :: fun(), + Trans :: atom()) + -> {'result', Nodes :: [] | [Node::pubsubNode()]} + ). + transaction(Host, Action, Trans) -> transaction(fun() -> {result, lists:foldl(Action, [], tree_call(Host, get_nodes, [Host]))} end, Trans). + +-spec(transaction/2 :: + ( + Fun :: fun(), + Trans :: atom()) + -> {'result', Result::_} | {'error', Error::_} + ). + transaction(Fun, Trans) -> case catch mnesia:Trans(Fun) of {result, Result} -> {result, Result}; @@ -3889,30 +4462,39 @@ extended_error(Error, unsupported, Feature) -> extended_error(Error, unsupported, [?XMLATTR('feature', Feature)]); extended_error(Error, Ext, ExtAttrs) -> - Pubsub_Err = #xmlel{ns = ?NS_PUBSUB_ERRORS, name = Ext, attrs = ExtAttrs}, + %Pubsub_Err = #xmlel{ns = ?NS_PUBSUB_ERRORS, name = Ext, attrs = ExtAttrs}, exmpp_xml:append_child(exmpp_stanza:error(?NS_JABBER_CLIENT, Error), - Pubsub_Err). + #xmlel{ns = ?NS_PUBSUB_ERRORS, name = Ext, attrs = ExtAttrs}). %% Give a uniq identifier +-spec(uniqid/0 :: () -> Id::binary()). + uniqid() -> {T1, T2, T3} = now(), - lists:flatten(io_lib:fwrite("~.16B~.16B~.16B", [T1, T2, T3])). + list_to_binary(lists:flatten(io_lib:fwrite("~.16B~.16B~.16B", [T1, T2, T3]))). -% node attributes + % node attributes nodeAttr(Node) when is_list(Node) -> [?XMLATTR('node', Node)]; nodeAttr(Node) -> [?XMLATTR('node', node_to_string(Node))]. -% item attributes + % item attributes itemAttr([]) -> []; itemAttr(ItemId) -> [?XMLATTR('id', ItemId)]. -% build item elements from item list -itemsEls(Items) -> - lists:map(fun(#pubsub_item{id = {ItemId, _}, payload = Payload}) -> - #xmlel{ns = ?NS_PUBSUB, name = 'item', attrs = itemAttr(ItemId), children = Payload} - end, Items). + + % build item elements from item list +-spec(itemsEls/1 :: + ( + PubsubItems::[PubsubItem::pubsubItem()]) + -> Items::[Item::#xmlel{name::'item',ns::?NS_PUBSUB}] + ). + +itemsEls(PubsubItems) -> + [#xmlel{ns = ?NS_PUBSUB, name = 'item', attrs = itemAttr(ItemId), children = Payload} + || #pubsub_item{id = {ItemId, _}, payload = Payload} <- PubsubItems]. + add_message_type(#xmlel{name='message'} = El, Type) -> exmpp_stanza:set_type(El, Type); add_message_type(El, _Type) -> El. @@ -3954,13 +4536,13 @@ subid_shim(SubIds) -> [#xmlel{ns = ?NS_PUBSUB, name ='header', attrs = [?XMLATTR('name', <<"SubId">>)], children = [?XMLCDATA(SubId)]} - || SubId <- SubIds]. + || SubId <- SubIds]. extended_headers(JIDs) -> [#xmlel{ns = ?NS_ADDRESS, name = 'address', attrs = [?XMLATTR('type', <<"replyto">>), ?XMLATTR('jid', JID)]} - || JID <- JIDs]. + || JID <- JIDs]. feature_check_packet(allow, _User, Server, Pres, {From, _To, El}, in) -> Host = list_to_binary(host(Server)), @@ -3988,8 +4570,8 @@ is_feature_supported(_, []) -> true; is_feature_supported(#xmlel{name = 'presence', children = Els}, Feature) -> case mod_caps:read_caps(Els) of - nothing -> false; - Caps -> lists:member(Feature ++ "+notify", mod_caps:get_features(Caps)) + nothing -> false; + Caps -> lists:member(Feature ++ "+notify", mod_caps:get_features(Caps)) end. on_user_offline(_, JID, _) -> @@ -4004,56 +4586,56 @@ purge_offline({User, Server, _} = LJID) -> Host = host(Server), Plugins = plugins(Host), Result = lists:foldl( - fun(Type, {Status, Acc}) -> - case lists:member("retrieve-affiliations", features(Type)) of - false -> - {{error, extended_error('feature-not-implemented', unsupported, "retrieve-affiliations")}, Acc}; - true -> - {result, Affiliations} = node_action(Host, Type, get_entity_affiliations, [Host, JID]), - {Status, [Affiliations|Acc]} - end - end, {ok, []}, Plugins), + fun(Type, {Status, Acc}) -> + case lists:member("retrieve-affiliations", features(Type)) of + false -> + {{error, extended_error('feature-not-implemented', unsupported, "retrieve-affiliations")}, Acc}; + true -> + {result, Affiliations} = node_action(Host, Type, get_entity_affiliations, [Host, JID]), + {Status, [Affiliations|Acc]} + end + end, {ok, []}, Plugins), case Result of {ok, Affiliations} -> lists:foreach( - fun({#pubsub_node{id = {_, NodeId}, options = Options, type = Type}, Affiliation}) - when Affiliation == 'owner' orelse Affiliation == 'publisher' -> - Action = fun(#pubsub_node{type = NType, idx = Nidx}) -> - node_call(NType, get_items, [Nidx, service_jid(Host)]) - end, - case transaction(Host, NodeId, Action, sync_dirty) of - {result, {_, []}} -> - true; - {result, {_, Items}} -> - Features = features(Type), - case - {lists:member("retract-items", Features), - lists:member("persistent-items", Features), - get_option(Options, persist_items), - get_option(Options, purge_offline)} - of - {true, true, true, true} -> - ForceNotify = get_option(Options, notify_retract), - lists:foreach( - fun(#pubsub_item{id = {ItemId, _}, modification = {_, Modification}}) -> + fun({#pubsub_node{id = {_, NodeId}, options = Options, type = Type}, Affiliation}) + when Affiliation == 'owner' orelse Affiliation == 'publisher' -> + Action = fun(#pubsub_node{type = NType, idx = Nidx}) -> + node_call(NType, get_items, [Nidx, service_jid(Host)]) + end, + case transaction(Host, NodeId, Action, sync_dirty) of + {result, {_, []}} -> + true; + {result, {_, Items}} -> + Features = features(Type), + case + {lists:member("retract-items", Features), + lists:member("persistent-items", Features), + get_option(Options, persist_items), + get_option(Options, purge_offline)} + of + {true, true, true, true} -> + ForceNotify = get_option(Options, notify_retract), + lists:foreach( + fun(#pubsub_item{id = {ItemId, _}, modification = {_, Modification}}) -> case Modification of {User, Server, _} -> delete_item(Host, NodeId, LJID, ItemId, ForceNotify); _ -> true end; - (_) -> + (_) -> true - end, Items); - _ -> - true - end; - Error -> - Error - end; - (_) -> - true - end, lists:usort(lists:flatten(Affiliations))); + end, Items); + _ -> + true + end; + Error -> + Error + end; + (_) -> + true + end, lists:usort(lists:flatten(Affiliations))); {Error, _} -> ?DEBUG("on_user_offline ~p", [Error]) end. @@ -4061,12 +4643,12 @@ purge_offline({User, Server, _} = LJID) -> notify_owners(false, _, _, _, _, _) -> true; notify_owners(true, JID, Host, Node, Owners, State) -> Message = #xmlel{name = 'message', ns = ?NS_JABBER_CLIENT, - children = [#xmlel{name = 'pubsub', ns = ?NS_PUBSUB, - children = [#xmlel{name = 'subscription', ns = ?NS_PUBSUB, - attrs = [?XMLATTR('node', Node), - ?XMLATTR('jid', exmpp_jid:prep_to_binary(exmpp_jid:make(JID))), - ?XMLATTR('subscription', State)]}]}]}, + children = [#xmlel{name = 'pubsub', ns = ?NS_PUBSUB, + children = [#xmlel{name = 'subscription', ns = ?NS_PUBSUB, + attrs = [?XMLATTR('node', Node), + ?XMLATTR('jid', exmpp_jid:prep_to_binary(exmpp_jid:make(JID))), + ?XMLATTR('subscription', State)]}]}]}, lists:foreach( fun(Owner) -> - ejabberd_router:route(exmpp_jid:make(Host), exmpp_jid:make(Owner), Message) + ejabberd_router:route(exmpp_jid:make(Host), exmpp_jid:make(Owner), Message) end, Owners). diff --git a/src/mod_pubsub/node_dag.erl b/src/mod_pubsub/node_dag.erl index 7f92cbc57..553f182d7 100644 --- a/src/mod_pubsub/node_dag.erl +++ b/src/mod_pubsub/node_dag.erl @@ -319,7 +319,7 @@ get_entity_subscriptions(Host, JID) -> ( NodeIdx :: nodeIdx()) -> {'result', [] - | [{Entity::fullUsr(), 'none'}] + %| [{Entity::fullUsr(), 'none'}] | [{Entity::fullUsr(), Subscription::subscription(), SubId::subId()}]} ). diff --git a/src/mod_pubsub/node_flat.erl b/src/mod_pubsub/node_flat.erl index 1d1096461..649563ff4 100644 --- a/src/mod_pubsub/node_flat.erl +++ b/src/mod_pubsub/node_flat.erl @@ -824,7 +824,7 @@ get_entity_subscriptions(Host, #jid{node = U, domain = S, resource = R} = _JID) ( NodeIdx :: nodeIdx()) -> {'result', [] - | [{Entity::fullUsr(), 'none'}] + %| [{Entity::fullUsr(), 'none'}] %| [{Entity::fullUsr(), Subscription::subscription()}] %% still useful case ? | [{Entity::fullUsr(), Subscription::subscription(), SubId::subId()}]} ). diff --git a/src/mod_pubsub/pubsub.hrl b/src/mod_pubsub/pubsub.hrl index 832b4d8c4..0da5d3881 100644 --- a/src/mod_pubsub/pubsub.hrl +++ b/src/mod_pubsub/pubsub.hrl @@ -55,7 +55,7 @@ %%% Server = binary() %%% Resource = undefined. --type(hostPEP() :: {User::binary(), Server::binary, Resource::undefined}). +-type(hostPEP() :: {User::binary(), Server::binary(), Resource::undefined}). %%% @type host() = hostPubsub() | hostPEP().