Comparison

util/pubsub.lua @ 6439:d58ad8bd244b

util.pubsub: Add support for limiting the number of item in a node (default to 20)
author Kim Alvefur <zash@zash.se>
date Sun, 28 Sep 2014 01:50:00 +0200
parent 6437:3f1f11dfdf10
child 6442:0f4025abbe8f
child 6515:c9a72c64c3e2
comparison
equal deleted inserted replaced
6438:b1c40054b59d 6439:d58ad8bd244b
10 broadcaster = function () end; 10 broadcaster = function () end;
11 get_affiliation = function () end; 11 get_affiliation = function () end;
12 capabilities = {}; 12 capabilities = {};
13 } }; 13 } };
14 local default_node_config = { __index = { 14 local default_node_config = { __index = {
15 ["pubsub#max_items"] = "20";
15 } }; 16 } };
16 17
17 function new(config) 18 function new(config)
18 config = config or {}; 19 config = config or {};
19 return setmetatable({ 20 return setmetatable({
260 return i; 261 return i;
261 end 262 end
262 end 263 end
263 end 264 end
264 265
266 local function trim_items(data, max)
267 max = tonumber(max);
268 if not max or #data <= max then return end
269 repeat
270 data[t_remove(data, 1)] = nil;
271 until #data <= max
272 end
273
265 function service:publish(node, actor, id, item) 274 function service:publish(node, actor, id, item)
266 -- Access checking 275 -- Access checking
267 if not self:may(node, actor, "publish") then 276 if not self:may(node, actor, "publish") then
268 return false, "forbidden"; 277 return false, "forbidden";
269 end 278 end
281 end 290 end
282 local node_data = self.data[node]; 291 local node_data = self.data[node];
283 remove_item_by_id(node_data, id); 292 remove_item_by_id(node_data, id);
284 node_data[#node_data + 1] = id; 293 node_data[#node_data + 1] = id;
285 node_data[id] = item; 294 node_data[id] = item;
295 trim_items(node_data, node_obj.config["pubsub#max_items"]);
286 self.events.fire_event("item-published", { node = node, actor = actor, id = id, item = item }); 296 self.events.fire_event("item-published", { node = node, actor = actor, id = id, item = item });
287 self.config.broadcaster("items", node, node_obj.subscribers, item); 297 self.config.broadcaster("items", node, node_obj.subscribers, item);
288 return true; 298 return true;
289 end 299 end
290 300
425 end 435 end
426 436
427 for k,v in pairs(new_config) do 437 for k,v in pairs(new_config) do
428 node_obj.config[k] = v; 438 node_obj.config[k] = v;
429 end 439 end
440 trim_items(self.data[node], node_obj.config["pubsub#max_items"]);
430 441
431 return true; 442 return true;
432 end 443 end
433 444
434 return _M; 445 return _M;