plugins/uptime.lua

1
local verse = require "verse";
2
 
3
local xmlns_last = "jabber:iq:last";
4
 
5
local function set_uptime(self, uptime_info)
6
	self.starttime = uptime_info.starttime;
7
end
8
 
9
function verse.plugins.uptime(stream)
10
	stream.uptime = { set = set_uptime };
11
	stream:hook("iq/"..xmlns_last, function (stanza)
12
		if stanza.attr.type ~= "get" then return; end
13
		local reply = verse.reply(stanza)
14
			:tag("query", { seconds = tostring(os.difftime(os.time(), stream.uptime.starttime)), xmlns = xmlns_last });
15
		stream:send(reply);
16
		return true;
17
	end);
18
 
19
	function stream:query_uptime(target_jid, callback)
20
		callback = callback or function (uptime) return stream:event("uptime/response", uptime); end
21
		stream:send_iq(verse.iq({ type = "get", to = target_jid })
22
			:tag("query", { xmlns = xmlns_last }),
23
			function (reply)
24
				local query = reply:get_child("query", xmlns_last);
25
				if reply.attr.type == "result" then
26
					local seconds = tonumber(query.attr.seconds);
27
					callback({
28
						seconds = seconds or nil;
29
						});
30
				else
31
					local type, condition, text = reply:get_error();
32
					callback({
33
						error = true;
34
						condition = condition;
35
						text = text;
36
						type = type;
37
						});
38
				end
39
			end);
40
	end
41
	return true;
42
end