aboutsummaryrefslogtreecommitdiffstats
path: root/util/pubsub.lua
blob: f667295e36599a919ca79d6b9648b18f9b89e9c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
module("pubsub", package.seeall);

local service = {};
local service_mt = { __index = service };

local default_config = {
	broadcaster = function () end;
	get_affiliation = function () end;
	capabilities = {};
};

function new(config)
	config = config or {};
	return setmetatable({
		config = setmetatable(config, { __index = default_config });
		affiliations = {};
		nodes = {};
	}, service_mt);
end

function service:add_subscription(node, actor, jid)
	local node_obj = self.nodes[node];
	if not node_obj then
		return false, "item-not-found";
	end
	node_obj.subscribers[jid] = true;
	return true;
end

function service:remove_subscription(node, actor, jid)
	local node_obj = self.nodes[node];
	if not node_obj then
		return false, "item-not-found";
	end
	if not node_obj.subscribers[jid] then
		return false, "not-subscribed";
	end
	node_obj.subscribers[jid] = nil;
	return true;
end

function service:get_subscription(node, actor, jid)
	local node_obj = self.nodes[node];
	if node_obj then
		return node_obj.subscribers[jid];
	end
end

function service:create(node, actor)
	if not self.nodes[node] then
		self.nodes[node] = { name = node, subscribers = {}, config = {}, data = {} };
		return true;
	end
	return false, "conflict";
end

function service:publish(node, actor, id, item)
	local node_obj = self.nodes[node];
	if not node_obj then
		node_obj = { name = node, subscribers = {}, config = {}, data = {} };
		self.nodes[node] = node_obj;
	end
	node_obj.data[id] = item;
	self.cb.broadcaster(node, node_obj.subscribers, item);
	return true;
end

function service:retract(node, actor, id, retract)
	local node_obj = self.nodes[node];
	if (not node_obj) or (not node_obj.data[id]) then
		return false, "item-not-found";
	end
	node_obj.data[id] = nil;
	if retract then
		self.cb.broadcaster(node, node_obj.subscribers, retract);
	end
	return true
end

function service:get(node, actor, id)
	local node_obj = self.nodes[node];
	if node_obj then
		if id then
			return { node_obj.data[id] };
		else
			return node_obj.data;
		end
	end
end

function service:get_nodes(actor)
	return true, self.nodes;
end

return _M;