plugins/ping.lua

Thu, 23 Mar 2023 18:56:32 +0000

author
Matthew Wild <mwild1@gmail.com>
date
Thu, 23 Mar 2023 18:56:32 +0000
changeset 485
c9a144591649
parent 457
73d4eb93657b
child 490
6b2f31da9610
permissions
-rw-r--r--

component: Avoid adding to the global stream metatable

This allows component and client connections to be made side-by-side.
Previous to this change, loading this connection module would break the
ability to make client connections, due to overriding stream methods such as
:reopen() and :reset().

A next step would be to share the methods that the two connection modules have
in common.

local verse = require "verse";
local gettime = require"socket".gettime;
local new_id = require "util.id".short;

local xmlns_ping = "urn:xmpp:ping";

function verse.plugins.ping(stream)
	function stream:ping(jid, callback)
		local t = gettime();
		local id = new_id();
		local ping = verse.iq{ id = id, to = jid, type = "get" }:tag("ping", { xmlns = xmlns_ping });
		stream:send_iq(ping,
			function (reply)
				if reply.attr.type == "error" then
					local type, condition, text = reply:get_error();
					if condition ~= "service-unavailable" and condition ~= "feature-not-implemented" then
						callback(nil, jid, { type = type, condition = condition, text = text });
						return;
					end
				end
				callback(gettime()-t, jid);
			end);
		return id;
	end
	stream:hook("iq/"..xmlns_ping, function(stanza)
		return stream:send(verse.reply(stanza));
	end);
	return true;
end

mercurial