util/broadcast.lua

1
-- Prosody IM
2
-- Copyright (C) 2008-2010 Matthew Wild
3
-- Copyright (C) 2008-2010 Waqas Hussain
4
-- 
5
-- This project is MIT/X11 licensed. Please see the
6
-- COPYING file in the source package for more information.
7
--
8
 
9
 
10
local ipairs, pairs, setmetatable, type =
11
      ipairs, pairs, setmetatable, type;
12
 
13
module "pubsub"
14
 
15
local pubsub_node_mt = { __index = _M };
16
 
17
function new_node(name)
18
	return setmetatable({ name = name, subscribers = {} }, pubsub_node_mt);
19
end
20
 
21
function set_subscribers(node, subscribers_list, list_type)
22
	local subscribers = node.subscribers;
23
	
24
	if list_type == "array" then
25
		for _, jid in ipairs(subscribers_list) do
26
			if not subscribers[jid] then
27
				node:add_subscriber(jid);
28
			end
29
		end
30
	elseif (not list_type) or list_type == "set" then
31
		for jid in pairs(subscribers_list) do
32
			if type(jid) == "string" then
33
				node:add_subscriber(jid);
34
			end
35
		end
36
	end
37
end
38
 
39
function get_subscribers(node)
40
	return node.subscribers;
41
end
42
 
43
function publish(node, item, dispatcher, data)
44
	local subscribers = node.subscribers;
45
	for i = 1,#subscribers do
46
		item.attr.to = subscribers[i];
47
		dispatcher(data, item);
48
	end
49
end
50
 
51
function add_subscriber(node, jid)
52
	local subscribers = node.subscribers;
53
	if not subscribers[jid] then
54
		local space = #subscribers;
55
		subscribers[space] = jid;
56
		subscribers[jid] = space;
57
	end
58
end
59
 
60
function remove_subscriber(node, jid)
61
	local subscribers = node.subscribers;
62
	if subscribers[jid] then
63
		subscribers[subscribers[jid]] = nil;
64
		subscribers[jid] = nil;
65
	end
66
end
67
 
68
return _M;