849
|
1
|
|
2 local ipairs, pairs, setmetatable, type =
|
|
3 ipairs, pairs, setmetatable, type;
|
|
4
|
|
5 module "pubsub"
|
|
6
|
|
7 local pubsub_node_mt = { __index = _M };
|
|
8
|
|
9 function new_node(name)
|
|
10 return setmetatable({ name = name, subscribers = {} }, pubsub_node_mt);
|
|
11 end
|
|
12
|
|
13 function set_subscribers(node, subscribers_list, list_type)
|
|
14 local subscribers = node.subscribers;
|
|
15
|
|
16 if list_type == "array" then
|
|
17 for _, jid in ipairs(subscribers_list) do
|
|
18 if not subscribers[jid] then
|
|
19 node:add_subscriber(jid);
|
|
20 end
|
|
21 end
|
|
22 elseif (not list_type) or list_type == "set" then
|
|
23 for jid in pairs(subscribers_list) do
|
|
24 if type(jid) == "string" then
|
|
25 node:add_subscriber(jid);
|
|
26 end
|
|
27 end
|
|
28 end
|
|
29 end
|
|
30
|
|
31 function get_subscribers(node)
|
|
32 return node.subscribers;
|
|
33 end
|
|
34
|
|
35 function publish(node, item, dispatcher, data)
|
|
36 local subscribers = node.subscribers;
|
|
37 for i = 1,#subscribers do
|
|
38 item.attr.to = subscribers[i];
|
|
39 dispatcher(data, item);
|
|
40 end
|
|
41 end
|
|
42
|
|
43 function add_subscriber(node, jid)
|
|
44 local subscribers = node.subscribers;
|
|
45 if not subscribers[jid] then
|
|
46 local space = #subscribers;
|
|
47 subscribers[space] = jid;
|
|
48 subscribers[jid] = space;
|
|
49 end
|
|
50 end
|
|
51
|
|
52 function remove_subscriber(node, subscriber)
|
|
53 local subscribers = node.subscribers;
|
|
54 if subscribers[jid] then
|
|
55 subscribers[subscribers[jid]] = nil;
|
|
56 subscribers[jid] = nil;
|
|
57 end
|
|
58 end
|
|
59
|
|
60 return _M;
|