comparison mod_listusers/mod_listusers.lua @ 1055:3dd909e87143

mod_listusers: added (+config support; -assert tracebacks; +user friendly connection errors; -unneded repeat-until cycle, which braked module)
author Vadim Misbakh-Soloviov <mva@mva.name>
date Fri, 07 Jun 2013 08:43:03 +0700
parents
children b307b72ae527
comparison
equal deleted inserted replaced
1054:432dc4056114 1055:3dd909e87143
1 function module.command(args)
2 local action = table.remove(args, 1);
3 if not action then -- Default, list registered users
4 local data_path = CFG_DATADIR or "data";
5 if not pcall(require, "luarocks.loader") then
6 pcall(require, "luarocks.require");
7 end
8 local lfs = require "lfs";
9 function decode(s)
10 return s:gsub("%%([a-fA-F0-9][a-fA-F0-9])", function (c)
11 return string.char(tonumber("0x"..c));
12 end);
13 end
14 for host in lfs.dir(data_path) do
15 local accounts = data_path.."/"..host.."/accounts";
16 if lfs.attributes(accounts, "mode") == "directory" then
17 for user in lfs.dir(accounts) do
18 if user:sub(1,1) ~= "." then
19 print(decode(user:gsub("%.dat$", "")).."@"..decode(host));
20 end
21 end
22 end
23 end
24 elseif action == "--connected" then -- List connected users
25 local socket = require "socket";
26 local default_local_interfaces = { };
27 if socket.tcp6 and config.get("*", "use_ipv6") ~= false then
28 table.insert(default_local_interfaces, "::1");
29 end
30 if config.get("*", "use_ipv4") ~= false then
31 table.insert(default_local_interfaces, "127.0.0.1");
32 end
33
34 local console_interfaces = config.get("*", "console_interfaces")
35 or config.get("*", "local_interfaces")
36 or default_local_interfaces
37 console_interfaces = type(console_interfaces)~="table"
38 and {console_interfaces} or console_interfaces;
39
40 local console_ports = config.get("*", "console_ports") or 5582
41 console_ports = type(console_ports) ~= "table" and { console_ports } or console_ports;
42
43 local st, conn = pcall(assert,socket.connect(console_interfaces[1], console_ports[1]));
44 if (not st) then print("Error"..(conn and ": "..conn or "")); return 1; end
45
46 conn:send("c2s:show()\n");
47 conn:settimeout(1); -- Only hit in case of failure
48
49 repeat local line = conn:receive()
50 if not line then break; end
51 local jid = line:match("^| (.+)$");
52 if jid then
53 jid = jid:gsub(" %- (%w+%(%d+%))$", "\t%1");
54 print(jid);
55 elseif line:match("^| OK:") then
56 return 0;
57 end
58 until false;
59 end
60 return 0;
61 end